Python hex()

In this post, we will see about Python hex() function.
Python hex() method converts an int to hexadecimal with ‘0x’ as prefix.If x is not an Python int then it needs to define __index__ method which returns an int.


Syntax

x is the int which you want to convert to hexadecimal.


Return

It returns hexadecimal representation of int.


Example

Let’s understand with help of simple example:

print('Hexadecimal representation of 9:',hex(9)) print('Hexadecimal representation of 13:',hex(13)) print('Hexadecimal representation of 101:',hex(101))

Output:

Hexadecimal representation of 9: 0x9
Hexadecimal representation of 13: 0xd
Hexadecimal representation of 101: 0x65

hex() for user defined class

You need to implement __index__() method which returns an int in case of user defined class.We are simply returning 30 from below __index__() and when you call hex(country), it internally executes __index__() of country class only.

class Country: name = 'India' population = 10000 def __index__(self): return 30 country = Country() print(hex(country))

Output:

0x1e

That’s all about hex() function in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *