String to Hex in Python

Hexadecimal values have a base of 16. In Python, hexadecimal strings are prefixed with 0x
.
The hex()
function is used to convert a decimal integer to its respective hexadecimal number. For example,
a = 102
print(hex(a))
Output:
0x66
We can also convert float values to hexadecimal using the hex()
function with the float()
function. The following code implements this.
a = 102.18
print(float.hex(a))
Output:
0x1.98b851eb851ecp+6
We cannot convert a string using this function. So if we have a situation where we have a hexadecimal string and want to convert it into the hexadecimal number, we cannot do it directly. For such cases, we have to convert this string to the required decimal value using the int()
function and then convert it to the hexadecimal number using the hex()
function discussed earlier.
The following code shows this.
hex_s = "0xEFA"
a = int(hex_s, 16)
hex_n = hex(a)
print(hex_n)
Output:
0xEFA
Characters in the string do not have any corresponding hexadecimal value. However, if we convert a string to a bytes type object, using the encode()
function, we can convert it to its hexadecimal value using the hex()
function.
For example,
s = "Sample String".encode("utf-8")
print(s.hex())
Output:
53616d706c6520537472696e67
In the above code, we encode the string in the utf-8
type and convert it into byte types.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedInRelated Article - Python String
- Remove Commas From String in Python
- Check a String Is Empty in a Pythonic Way
- Convert a String to Variable Name in Python
- Remove Whitespace From a String in Python
- Extract Numbers From a String in Python
- Convert String to Datetime in Python