Convert Integer to Hex Format

To convert integer to hex format string in Python, call format(value, format) function and pass the integer for value parameter, and ‘x’ or ‘X’ for format parameter.

‘x’ for format parameter formats the given integer into lower-case letters for digits above 9.

‘X’ for format parameter formats the given integer into upper-case letters for digits above 9.

format() function returns a string with the hex representation of given integer.

Python format() builtin function

Examples

Convert Integer to Upper-case Hex Format

In this example, we take an integer value and format it to Hex upper-case, using format() builtin function.

Python Program

</>
Copy
a = 31
result = format(a, 'X')
print(result)

Output

1F

Convert Integer to Lower-case Hex Format

In this example, we take an integer value and format it to Hex lower-case, using format() builtin function.

Python Program

</>
Copy
a = 31
result = format(a, 'x')
print(result)

Output

1f

Conclusion

In this Python Tutorial, we learned how to format an integer to hexadecimal using format() function.