Python hex() With Examples

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”.

We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer.

The input integer argument can be in any base such as binary, octal etc. Python will take care of converting them to hexadecimal format.

Python hex() example

Let’s look into some simple examples of converting integer to hexadecimal number.

Output:

Python hex() with object

Let’s create a custom class and define __index__() function so that we can use hex() function with it.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: