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.

Download  Run Code

 
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.

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

That’s all about converting an integer to a hex string in Python.

 
Also See:

Convert a hex string to an integer in Python