hex() is one of the important method in Python. This method is used to convert any integer value to hexadecimal string value. If it is not an integer, or if it is an another object, it should have one index() method defined, that returns one integer value.
In this post, we will learn how to use hex method with examples.
hex method is defined as like below:
Here, i is an integer value and it returns one string, i.e. its hexadecimal value that is prefixed with 0x.
Let’s take a look at how to use hex() with examples.
print(hex(100)) print(hex(-100)) print(hex(-30))
It will print the below output:
0x64 -0x64 -0x1e
We can also find the hex value for a floating point value. For that, we need to use float.hex() method. For example,
This will throw one TypeError:
TypeError: 'float' object cannot be interpreted as an integer
So, we can use float.hex to parse a floating point value:
It will print:
We can also convert a hexadecimal value to integer. For that, we need to use the int() method. This method takes one hexadecimal value and convert that to an integer.
As explained above, we need to define the index method that should return one integer value.
class SampleObject: def __index__(self): return 10 obj = SampleObject() print(hex(obj))
Here, SampleObject is a class that has index() method that returns one integer value. If you run this code, it will print the below output:
Which is the hexadecimal value of 10.
- 3 ways to create a list of alternate elements in Python
- Python string replace method explanation with example
- Python program to remove commas from a string
- Python program to append a string to a list
- Python program to append/add or update key/value pairs in a dictionary
- How to do floor division in python