Home Python Bytes Methods decode() Python bytes.decode() Method Definition bytes.decode() interprets the bytes as text in a given encoding and returns a str. The default encoding is "utf-8". It is the reverse of str.encode() .
If the bytes are not valid in that encoding, the errors argument decides what happens: "strict" (the default) raises UnicodeDecodeError, "ignore" drops bad bytes, "replace" inserts U+FFFD, and "backslashreplace" writes escapes like \xff.
bytes.decode() is a method of the built-in bytes type : call it on a bytes object with dot notation, such as data.decode(...). No import is needed, and bytearray objects have the same method.
Syntax Optionally pass an encoding and an error handler.
text = data.decode()
text = data.decode(encoding)
text = data.decode(encoding, errors) Call What it does b"Hi".decode()Returns 'Hi'. b"caf\xc3\xa9".decode("utf-8")Returns 'café': two bytes become one character. b"\xff".decode("utf-8", "replace")Returns a one-character str holding the replacement character U+FFFD.
Always decode with the same encoding that was used to encode; a wrong but valid encoding does not raise, it silently produces the wrong characters.
Method signatures bytes.decode(encoding='utf-8', errors='strict')
# returns a str
# errors: 'strict', 'ignore', 'replace', 'backslashreplace', ... Parameters Parameter Description encoding Optional. The codec name, such as "utf-8", "ascii", "latin-1", or "cp1252". Default "utf-8". errors Optional. How to handle invalid bytes. Default "strict".
Return Value Return Value Description str The decoded text.
Python Examples 1. Decode UTF-8 2. Error handlers 3. Decode a reply Example 1 — Decode UTF-8 and Count Characters Decode a word that ends with a two-byte letter, compare lengths, and see what a different codec makes of the same bytes.
data = b"caf\xc3\xa9"
text = data.decode()
print(ascii(text))
print(len(data), len(text))
print(data.decode("latin-1") == "caf\u00c3\u00a9") How It Works Default codec. With no argument, UTF-8 combines \xc3\xa9 into the single character U+00E9.Bytes vs characters. Five bytes become four characters.Wrong codec, no error. Latin-1 maps each byte to its own character, producing two wrong characters instead of one, without raising.Example 2 — Handle Invalid Bytes with errors= \xff can never appear in UTF-8. Catch the strict error, then compare the three most useful error handlers.
raw = b"ok\xffend"
try:
raw.decode("utf-8")
except UnicodeDecodeError as err:
print("bad byte at position", err.start)
print(ascii(raw.decode("utf-8", errors="replace")))
print(raw.decode("utf-8", errors="ignore"))
print(raw.decode("utf-8", errors="backslashreplace")) bad byte at position 2
'ok\ufffdend'
okend
ok\xffend How It Works Strict by default. The invalid byte raises UnicodeDecodeError, and err.start reports index 2.Replace. The bad byte becomes U+FFFD; ascii() prints it as \ufffd.Ignore. The bad byte is dropped silently, which can hide data problems.Backslash escapes. The text keeps a visible \xff marker, handy for logs.Example 3 — Decode a Server Reply and Spot Mojibake Decode an SMTP-style reply with the ASCII codec, parse it as text, then decode UTF-8 bytes with the wrong codec.
reply = b"220 mail.example.com ready\r\n"
line = reply.decode("ascii").rstrip()
code, _, message = line.partition(" ")
print(int(code), message)
print(type(line).__name__)
print(ascii("\u00fc".encode("utf-8").decode("cp1252"))) 220 mail.example.com ready
str
'\xc3\xbc' How It Works ASCII protocol. The reply is plain ASCII, so the strict ASCII codec is safe and catches unexpected bytes.Text methods now. After decoding, str.rstrip() and str.partition() work with str arguments.Mojibake. The two UTF-8 bytes of u with umlaut, read as Windows-1252, turn into two unrelated characters.Frequently Asked Questions How do I convert bytes to a string in Python? Call data.decode("utf-8"), or data.decode() since UTF-8 is the default.
What causes UnicodeDecodeError? The bytes are not valid in the chosen encoding, for example \xff in UTF-8. Use the right encoding or an errors handler.
What is the difference between errors="ignore" and errors="replace"? ignore drops invalid bytes; replace inserts the U+FFFD replacement character so you can see where data was lost.
How do I convert bytes to a str without decoding? str(data) gives the repr, such as "b'Hi'", which is rarely what you want. Use decode() for real text.
How do I go back from str to bytes? Use text.encode("utf-8") with the same encoding.
Next: bytes.endswith() Check whether bytes end with a suffix or any suffix from a tuple.
endswith() → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
10 people found this page helpful
Helpful Share Copy link Suggestion