- Format ints into string of hex
- Format options
- Format syntax
- Python – Convert Integer to Hexadecimal
- How to convert integer to hexadecimal in Python?
- Examples
- Positive integer to hexadecimal
- Negative integer to hexadecimal
- Integer to uppercase hexadecimal string
- Author
- Privacy Overview
- Print int as hex in Python
- How to print int as hex in Python?
- Using the format() function to print int as hex in Python.
- Using f-strings to print int as hex in Python.
Format ints into string of hex
I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 — «05», 16 — «10», etc. Example:
Input: [0,1,2,3,127,200,255], Output: 000102037fc8ff
#!/usr/bin/env python def format_me(nums): result = "" for i in nums: if i
12 Answers 12
Just for completeness, using the modern .format() syntax:
>>> numbers = [1, 15, 255] >>> ''.join(''.format(a) for a in numbers) '010FFF'
Besides the fact there's just a code snippet without any explanation (bad SO practice), I'm not sure why this answer is upvoted less than the one below it. Using the % syntax in Python 3 makes it backwards compatible. I highly recommend this solution over the other one.
The most recent and in my opinion preferred approach is the f-string :
Format options
The old format style was the % -syntax:
The more modern approach is the .format method:
[''.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string syntax:
Format syntax
Note that the f'' works as follows.
- The first part before : is the input or variable to format.
- The x indicates that the string should be hex. f'' is '64' , f'' (decimal) is '100' and f'' (binary) is '1100100' .
- The 02 indicates that the string should be left-filled with 0 's to minimum length 2 . f'' is '64' and f'' is ' 64' .
See pyformat for more formatting options.
Yes, f-strings all the way! Pyformat.info has a comprehensive collection of formatting tricks. Although it's slightly outdated, as it still considers the .format() method recent, everything noted there can also be used with f-strings too.
By far the best answer. Complete with all formatting options, each one using the simplest builtin way.
>>> str(bytearray([0,1,2,3,127,200,255])).encode('hex') '000102037fc8ff'
>>> bytearray([0,1,2,3,127,200,255]).hex() '000102037fc8ff'
This is likely the most performant option for Python 3 vs. the string formatting approaches (at least based on a few quick tests I ran myself; your mileage may vary).
A variant of this that will work on either Python 2 or 3 is: python import codecs ; str(codecs.encode(bytearray([0,1,2,3,127,200,255]), 'hex').decode())
Yet another option is binascii.hexlify :
a = [0,1,2,3,127,200,255] print binascii.hexlify(bytes(bytearray(a)))
This is also the fastest version for large strings on my machine.
In Python 2.7 or above, you could improve this even more by using
binascii.hexlify(memoryview(bytearray(a)))
saving the copy created by the bytes call.
Similar to my other answer, except repeating the format string:
>>> numbers = [1, 15, 255] >>> fmt = '' * len(numbers) >>> fmt.format(*numbers) '010FFF'
Just as a complementary to this answer: if you want to print the hex in lower case, use "<:02x>.format(number)`
Starting with Python 3.6, you can use f-strings:
a = [0,1,2,3,127,200,255] print str.join("", ("%02x" % i for i in a))
(Also note that your code will fail for integers in the range from 10 to 15.)
From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:
x= 255 print('the number is '.format(x))
Here are the base options
Type
'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.
Python – Convert Integer to Hexadecimal
In this tutorial, we will look at how to convert an integer to hexadecimal in Python with the help of some examples.
How to convert integer to hexadecimal in Python?
You can use the Python built-in hex() function to convert an integer to its hexadecimal form in Python. Pass the integer as an argument to the function. The following is the syntax –
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# convert int i to hexadecimal hex(i)
It returns the integer’s representation in the hexadecimal number system (base 16) as a lowercase string prefixed with '0x' .
Examples
Let’s look at some examples of using the above function to convert int to hex.
Positive integer to hexadecimal
Pass the integer as an argument to hex function.
# int variable num = 15 # int to hex num_hex = hex(num) # display hex and type print(num_hex) print(type(num_hex))
You can see that we get the hexadecimal representing the integer as a lowercase string with '0x' prefix.
If you do not want the prefix, you can use the string slice operation to remove the prefix from the returned hex string.
Negative integer to hexadecimal
Let’s now apply the same function to a negative integer.
# int variable num = -15 # int to hex num_hex = hex(num) # display hex and type print(num_hex) print(type(num_hex))
We get its hexadecimal string.
Integer to uppercase hexadecimal string
Alternatively, you can use the Python built-in format() function to convert an integer to its hexadecimal form. You can customize the format of the returned string.
For example, to convert an integer to an uppercase hexadecimal string, use the format string '#X' or 'X' .
# int variable num = 15 # int to hex num_hex = format(num, '#X') # display hex and type print(num_hex) print(type(num_hex))
We get the hexadecimal for the integer as an uppercase string.
With the format() function you can customize the returned hexadecimal string – with or without the prefix, uppercase or lowercase, etc.
# int variable num = 15 # int to hex print(f"Lowercase with prefix:") print(f"Lowercase without prefix: ") print(f"Uppercase with prefix: ") print(f"Uppercase without prefix: ")
Lowercase with prefix: 0xf Lowercase without prefix: f Uppercase with prefix: 0XF Uppercase without prefix: F
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
This website uses cookies to improve your experience. We'll assume you're okay with this, but you can opt-out if you wish.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
Print int as hex in Python
Python is a versatile programming language that provides many data types for the purpose of storing and representing data.
There is often a need to convert the stored content from one data type representation to another for making use of several functions that work only on a certain data type. This tutorial discusses one such conversion, which is to print int as a hex in Python.
In this article, we will see different ways available to represent an int value as a hexadecimal string.
How to print int as hex in Python?
There are several ways to print int as hex in Python, ranging from using the format function to making use of the in-built hex() function, all of which will be explained in the article below.
Using the format() function to print int as hex in Python.
The format() function is one of the ways to implement string formatting in Python. It is also capable of conversion of the given data from an int into a hexadecimal string.
The format() function makes use of a lot of specifiers, out of which the x specifier helps in carrying out the conversion in this task.
The hexadecimal string can be prefixed by 0x if we utilize #x instead of the general x format specifier.
The following code uses the format() function to print int as hex in Python.
The above code provides the following output:
If we use the format specifier in uppercase, that is, if we use #X instead of #x , then we can receive the hexadecimal string in uppercase as well.
The following code uses the format() function to print int as hex in uppercase in Python.
The above code provides the following output:
Using f-strings to print int as hex in Python.
Python 3.6 introduced f-strings, which is another way to implement string formatting in Python. It eliminates the need to always use the format() function, thereby reducing the size of the code, and also operates at a faster pace than the other two methods available to implement string formatting.
F-strings are easy to understand. Moreover, it is also capable of converting int to hex with the use of the right specifier which is x .
How it works is that the curly braces are utilized to enclose the integer, along with the format specifier and a colon to separate the both of them. Similar to the format() function, we use #x to add the 0x prefix to the hex output that we will receive.
The following code uses f-strings to print int as hex in Python.