Python hex() Function

Python hex() is a built-in function that converts an integer to corresponding hexadecimal string prefixed with 0x.

Python hex() Syntax


Python hex() function takes one parameter.

  • integer (required) – integer to be converted into the hexadecimal string.

The returned hexadecimal is prefixed with 0x. Example, 0x3e2.

Note: To convert floating point number to the hexadecimal string, hex function is used in following way.


Python hex() Example

>>> hex(10)
>>> hex(500)

>>> float.hex(100.0)
>>> float.hex(300.0)

These are the examples of how you convert integers or floating point numbers to hexadecimal strings.

Now some of you may wonder if there is any way to use hex() function without the prefix 0x. Well yes, there is a way.

Using Python hex() without 0x

This is achieved by truncating the first two character of the output. This might remove the perfixing 0x but we do not recommend doing this in real time programs.

>>> float.hex(300.0)[2:]

>>> hex(500)[2:]

Note that this method will break in negative values of the parameter.

Here is the example.

>>> hex(-500)

>>> #Now using [2:]
>>> hex(-500)[2:]

This is because we are truncating only first two characters, hence only - and 0 gets removed and x remains there.

So, for negative values 3 should be used instead of 2.

>>> hex(-500)[3:]