Convert between bytes and strings in Python
Decode bytes into text and encode strings into bytes with the right character encoding, including invalid-byte handling and Base64 output.
Call data.decode('utf-8') to turn UTF-8 bytes into a Python string. Call text.encode('utf-8') to turn text back into bytes. The decoding codec must match the encoding used to produce the bytes.
Convert in both directions
text = 'hello café'
data = text.encode('utf-8') # b'hello caf\xc3\xa9'
restored = data.decode('utf-8') # 'hello café'
assert restored == text
Python 3 str holds Unicode text; bytes holds byte values. A bytes literal such as b'abc' is valid, but non-ASCII characters cannot appear directly inside a bytes literal. Encode a string or use byte escapes instead.
Calling str(data) without an encoding produces a representation such as "b'abc'"; it does not decode the payload. You also cannot concatenate 'a' + b'b': choose text or bytes and convert first.
Deal with decoding errors deliberately
data = b'good\xffdata'
print(data.decode('utf-8', errors='replace')) # good�data
print(data.decode('utf-8', errors='ignore')) # gooddata
The default errors='strict' raises UnicodeDecodeError for invalid input. Check the file or protocol’s declared encoding before changing it; a GBK payload, for example, needs its actual codec. replace inserts a replacement character and ignore discards bytes, so both lose information. Neither discovers the correct encoding.
FAQ
How do I check whether a value is text or bytes?
Use isinstance(value, str) or isinstance(value, bytes). type(value) shows its concrete type.
What does Base64 encoding return?
base64.b64encode(data) returns bytes. For a textual Base64 value, use base64.b64encode(data).decode('ascii'). Base64 converts binary data to an ASCII representation; it is different from decoding the original bytes as text.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan