Python Convert a String to Hexadecimal and Vice Versa: A Beginner Guide – Python Tutorial

By | December 22, 2019

Sometimes, we need to convert a python string to hexadecimal to save, while we have to convert a hex to string when displaying it. How to do? To address this issue, we will use some python examples to tell you how to convert in this tutorial.

Python string to hex

To convert a python string to hex, we should convert it to a byte object.

Here is an example:

text = 'https://www.tutorialexample.com'
text_binary = text.encode(encoding='utf_8')

Convert Python String to Bytes Object for Python Beginners – Python Tutorial

Then we can convert this byte to hex.

hex_text = text_binary.hex()
print(hex_text)

Run this code, we will find the hex of https://www.tutorialexample.com is:

68747470733a2f2f7777772e7475746f7269616c6578616d706c652e636f6d

Python hex to string

We also can convert a hex to python string.

First, we should convert this hex string to byte.

text = bytes.fromhex(hex_text)

Then we will convert this byte to string.

text = text.decode(encoding='utf_8')
print(text)

Run this code, we will find the python string of hex 68747470733a2f2f7777772e7475746f7269616c6578616d706c652e636f6d is:

https://www.tutorialexample.com

Leave a Reply

Your email address will not be published. Required fields are marked *