Javaexercise.com

Python hex() Method

Python hex() method is a built-in method. It is used to convert an integer value to a hexadecimal string. It returns a lowercase string prefix with ‘0x’.


Signature

hex(x)

Parameter Description
x It is an integer argument and if not given, define an index method that returns an integer.


Return Value

   It returns a lowercase hexadecimal string.


Error: It returns an error (TypeError), if the argument is not an integer.


Python hex() Method Example

Let’s first understand, how this method works and what does it return?

# hex() method
a = hex(12)
b = hex(-12)
print(a)
print(b)
print(type(a))
Output
 0xc
 -0xc
 < class 'str'>

See, in the above example, hex() method returns hexadecimal string and the type of return value is string.


Python hex() Method Example

As we said, this method takes an integer argument only. If we give any other type of argument, it throws an error. See the example below.

# hex() method
a = hex("23")
print(a)
Output

 TypeError: 'str' object cannot be interpreted as an integer