In Python, hex() is a built-in function used to convert an integer to a hexadecimal string. Its syntax is as follows:

hex(x)

Here, x is an integer (can be positive or negative), and the return value is a hexadecimal string representing x. If x is not an int object, it must define an __index__() method.

hex() Function Examples

print(hex(255))   # 0xff
print(hex(1234))  # 0x4d2
print(hex(-123))  # -0x7b
print(hex(0xff))  # 0xff

class myclass:
    def __index__(self):
        return 1

a = myclass()
print(hex(a))  # 0x1

class myclass2:
    pass

b = myclass2()
# print(hex(b))    # TypeError
# print(hex(3.14)) # TypeError

The hexadecimal string returned by hex() includes the prefix 0x. If you need to remove the prefix, you can use string slicing. For example:

hex(255)[2:]