Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 177
    why doesn't str(text_bytes) work? This seems bizarre to me. Commented Mar 14, 2019 at 22:25
  • 79
    @CharlieParker Because str(text_bytes) can't specify the encoding. Depending on what's in text_bytes, text_bytes.decode('cp1250)` might result in a very different string to text_bytes.decode('utf-8'). Commented Mar 31, 2019 at 17:32
  • 19
    so str function does not convert to a real string anymore. One HAS to say an encoding explicitly for some reason I am to lazy to read through why. Just convert it to utf-8 and see if ur code works. e.g. var = var.decode('utf-8') Commented Apr 22, 2019 at 23:32
  • 20
    @CraigAnderson: unicode_text = str(bytestring, character_encoding) works as expected on Python 3. Though unicode_text = bytestring.decode(character_encoding) is more preferable to avoid confusion with just str(bytes_obj) that produces a text representation for bytes_obj instead of decoding it to text: str(b'\xb6', 'cp1252') == b'\xb6'.decode('cp1252') == '¶' and str(b'\xb6') == "b'\\xb6'" == repr(b'\xb6') != '¶' Commented Apr 12, 2020 at 5:11
  • 3
    Also, you can pass text=True to subprocess.run() or .Popen() and then you'll get a string back, no need to convert bytes. Or specify encoding="utf-8" to either function. Commented Sep 13, 2022 at 5:46