Python Introduction+

Python Flow Control+

Python Functions+

Python Native Data Types+

Python OOP+

File Handling+

# Python hex() Function

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

## Python hex() Syntax

``hex(integer)``

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.

``float.hex(number)``

## Python hex() Example

``````>>> hex(10)
'0xa'
>>> hex(500)
'0x1f4'

>>> float.hex(100.0)
'0x1.9000000000000p+6'
>>> float.hex(300.0)
'0x1.2c00000000000p+8'
``````

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:]
'1.2c00000000000p+8'

>>> hex(500)[2:]
'1f4'
``````

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

Here is the example.

``````>>> hex(-500)
'-0x1f4'

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

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:]
'1f4'``````