How to Convert Bytes to a String in Python
If you need to convert bytes to a string in Python, then you can do the following:
your_string = b'This works \xE2\x9C\x85'.decode("utf-8")
print(your_string)
Output:
This works ✅
Note that in the above example, we have converted a utf-8 string to.
The .decode() method is the standard way to convert bytes to a string in Python 3. You’ll run into this whenever you read binary data from files, HTTP responses, or subprocess output. The encoding parameter matters — if your data isn’t UTF-8, you’ll get a UnicodeDecodeError. Common alternatives are latin-1 (which never fails since it maps every byte) and ascii (for pure ASCII data). If you’re unsure of the encoding, the chardet library can detect it automatically.