Python string → hex is: encode text to bytes, then render those bytes as hex digits. The usual path is str.encode(...).hex().
Opposite direction: hex to string methods. Tools: String to Hex · Hex to String.
Default (Python 3): .hex()
text = "Hello"
print(text.encode("utf-8").hex()) # 48656c6c6f
print("你好".encode("utf-8").hex()) # e4bda0e5a5bd
# bytes → hex with separators (3.8+)
print(b"Hello".hex(":")) # 48:65:6c:6c:6f
binascii.hexlify
import binascii
hx = binascii.hexlify(b"Hello") # b'48656c6c6f'
print(hx.decode("ascii"))
Returns bytes of ASCII hex. Fine in binascii-heavy code; otherwise .hex() reads better. See unhexlify/hexlify notes.
Encoding is the real choice
s = "café"
print(s.encode("utf-8").hex())
print(s.encode("latin-1").hex()) # different bytes → different hex
Hex does not pick an encoding for you. Wrong encode → wrong hex → failed round-trips.
Round-trip
original = "café"
hx = original.encode("utf-8").hex()
back = bytes.fromhex(hx).decode("utf-8")
assert back == original
Do not hex a hex digest twice
import hashlib
print(hashlib.sha256(b"test").hexdigest()) # already hex
# hashlib.sha256(b"test").digest().hex() # equivalent; pick one style
- Prefer UTF-8 unless a protocol specifies otherwise.
- For large binary files, stream chunks and call
.hex()per chunk (or write raw bytes instead of hex if storage allows). - Hex doubles size — use for logs/APIs, not as a general DB format.
More: bytes.fromhex deep dive · hex overview.