Summary: in this tutorial, you’ll learn how to use the Python hex() function to convert an integer number to a lowercase hexadecimal string prefixed with 0x.
Introduction to the Python hex() function #
The hex() function accepts an integer and converts it to a lowercase hexadecimal string prefixed with 0x.
Here’s the syntax of the hex() function:
hex(x)The following example uses the hex() function to convert x from an integer (10) to a lowercase hexadecimal string prefixed with 0x:
x = 10
result = hex(10)
print(result) # ? 0xa
print(type(result)) # ? <class 'str'>Code language: PHP (php)If x is not an integer, it needs to have an __index__() that returns an integer. For example:
class MyClass:
def __init__(self, value):
self.value = value
def __index__(self):
return self.value
result = hex(MyClass(10))
print(result) # ? 0xaOutput:
0xaHow it works.
- First, define the
MyClassclass with a value attribute. - Second, initialize the value in the
__init__()method. - Third, implement the
__index__()method that returns the value. - Finally, create a new instance of
MyClassand pass it to thehex()function.
Another way to convert an integer to an uppercase or lower hexadecimal string is to use f-strings with a format. For example:
a = 10
h1 = f'{a:#x}'
print(h1) # ? 0xa
h2 = f'{a:x}'
print(h2) # ? a
h3 = f'{a:#X}'
print(h3) # ? 0XA
h3 = f'{a:X}'
print(h3) # ? ACode language: PHP (php)Summary #
- Use the Python hex() function to convert an integer to a lowercase hexadecimal string prefixed with
0x.
Was this tutorial helpful ?