Convert an integer to a hex string in Python
This post will discuss how to convert an integer to a hexadecimal string in Python.
1. Using hex() function
The Pythonic way to convert an integer to a hexadecimal string uses the built-in function hex(). It returns the hexadecimal string in lowercase, which is prefixed by 0x.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': i = 4095 h = hex(i) print(h) # '0xfff' |
To get an uppercase hexadecimal string or to get rid of the prefix, use any of the solutions discussed below.
2. Using format() function
Another option is to use the built-in function format(), which can convert an integer to a hexadecimal string using the x format specification. If you use #x, the hexadecimal string is prefixed by 0x. If you use X or #X, you can get an uppercase hexadecimal string.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': i = 4095 h = (format(i, '#x'), format(i, '#X'), format(i, 'x'), format(i, 'X')) print(h) # ('0xfff', '0XFFF', 'fff', 'FFF') |
3. Using f-strings
Starting with Python 3.6, you can use f-strings. You can do this by prefixing the string literal with f or F. The string literal should be enclosed within the curly braces {} and should contain the integer, followed by the formatting specification x separated by a colon :.
To prefix the hexadecimal string by 0x, use #x, and to get an uppercase hexadecimal string, use X or #X. Here’s how the code would look like:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': i = 4095 h = (f'{i:#x}', f'{i:#X}', f'{i:x}', f'{i:X}') print(h) # ('0xfff', '0XFFF', 'fff', 'FFF') |
4. Using %x conversion
Before version 3.6, you may use the %x conversion to produce the hexadecimal string. If you use %#x, the hexadecimal literal value is prefixed by 0x. To get an uppercase hexadecimal string, use %X or %#X.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': i = 4095 h = ("%#x" % i, "%#X" % i, "%x" % i, "%X" % i) print(h) # ('0xfff', '0XFFF', 'fff', 'FFF') |
That’s all about converting an integer to a hex string in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)