How to Convert String to Hex in Python
Convert any string to hexadecimal in Python with .encode().hex(), plus the reverse conversion, binascii, and non-ASCII handling.
Hexadecimal (hex) is base-16: digits 0–9 plus letters A–F. Every byte of data becomes exactly two hex digits. Python makes string-to-hex conversion a one-liner, and this guide covers the standard method, the reverse conversion, an older alternative, and non-ASCII text.
The Standard Method: .encode().hex()
Encode the string to bytes (UTF-8 by default), then call .hex():
text = "Hello"
hex_value = text.encode("utf-8").hex()
print(hex_value)
Output:
48656c6c6f
That is H = 48, e = 65, l = 6c, l = 6c, o = 6f. Note that Python’s .hex() returns lowercase letters. For uppercase, add .upper():
print("Hello".encode("utf-8").hex().upper())
Output:
48656C6C6F
Both forms represent the same value — only the display differs.
Converting Back: Hex to String
Use bytes.fromhex() and decode:
original = bytes.fromhex("48656c6c6f").decode("utf-8")
print(original)
Output:
Hello
bytes.fromhex() ignores spaces, so "48 65 6c 6c 6f" works too. It raises a ValueError if the string has an odd number of digits or contains non-hex characters.
Alternative: binascii.hexlify()
The older binascii module does the same job, but returns a bytes object instead of a string:
import binascii
result = binascii.hexlify(b"Hello")
print(result)
Output:
b'48656c6c6f'
Decode it with .decode("ascii") if you need a plain string. For new code, .encode().hex() is the recommended approach — it is shorter and needs no import.
Handling Non-ASCII Text
UTF-8 encodes ASCII characters as one byte each, but accented and non-Latin characters as two or more bytes:
print("café".encode("utf-8").hex())
Output:
636166c3a9
Here c = 63, a = 61, f = 66, and é becomes the two bytes c3 a9. The reverse works the same way:
print(bytes.fromhex("636166c3a9").decode("utf-8"))
Output:
café
If you need a different encoding (for example, UTF-16 or Latin-1), pass it to .encode() — but UTF-8 is the right default for almost everything, and it is what web tools and APIs expect.
FAQ
What is the simplest way to convert a string to hex in Python?
text.encode("utf-8").hex() — no imports needed.
Why is my hex output lowercase?
Python’s .hex() always returns lowercase. Call .upper() on the result if your project uses uppercase hex.
How do I convert hex back to a string?
bytes.fromhex(hex_string).decode("utf-8").
Why does café produce 10 hex digits for only 4 characters?
Because é is two UTF-8 bytes (c3 a9). Four characters, five bytes, and two hex digits per byte gives ten hex digits: 63 61 66 c3 a9.
Which method should I use in new code?
.encode().hex(). Keep binascii.hexlify() only for compatibility with older codebases.