python - Convert bytes to a string

ID : 173

viewed : 507

Tags : pythonstringpython-3.xpython

Top 5 Answer for python - Convert bytes to a string

vote vote


You need to decode the bytes object to produce a string:

>>> b"abcde" b'abcde'  # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8")  'abcde' 


vote vote


You need to decode the byte string and turn it in to a character (Unicode) string.

On Python 2

encoding = 'utf-8' 'hello'.decode(encoding) 


unicode('hello', encoding) 

On Python 3

encoding = 'utf-8' b'hello'.decode(encoding) 


str(b'hello', encoding) 
vote vote


I think this way is easy:

>>> bytes_data = [112, 52, 52] >>> "".join(map(chr, bytes_data)) 'p44' 
vote vote


If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use the ancient MS-DOS CP437 encoding:

PY3K = sys.version_info >= (3, 0)  lines = [] for line in stream:     if not PY3K:         lines.append(line)     else:         lines.append(line.decode('cp437')) 

Because encoding is unknown, expect non-English symbols to translate to characters of cp437 (English characters are not translated, because they match in most single byte encodings and UTF-8).

Decoding arbitrary binary input to UTF-8 is unsafe, because you may get this:

>>> b'\x00\x01\xffsd'.decode('utf-8') Traceback (most recent call last):   File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte 

The same applies to latin-1, which was popular (the default?) for Python 2. See the missing points in Codepage Layout - it is where Python chokes with infamous ordinal not in range.

UPDATE 20150604: There are rumors that Python 3 has the surrogateescape error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests, [binary] -> [str] -> [binary], to validate both performance and reliability.

UPDATE 20170116: Thanks to comment by Nearoo - there is also a possibility to slash escape all unknown bytes with backslashreplace error handler. That works only for Python 3, so even with this workaround you will still get inconsistent output from different Python versions:

PY3K = sys.version_info >= (3, 0)  lines = [] for line in stream:     if not PY3K:         lines.append(line)     else:         lines.append(line.decode('utf-8', 'backslashreplace')) 

See Python’s Unicode Support for details.

UPDATE 20170119: I decided to implement slash escaping decode that works for both Python 2 and Python 3. It should be slower than the cp437 solution, but it should produce identical results on every Python version.

# --- preparation  import codecs  def slashescape(err):     """ codecs error handler. err is UnicodeDecode instance. return     a tuple with a replacement for the unencodable part of the input     and a position where encoding should continue"""     #print err, dir(err), err.start, err.end, err.object[:err.start]     thebyte = err.object[err.start:err.end]     repl = u'\\x'+hex(ord(thebyte))[2:]     return (repl, err.end)  codecs.register_error('slashescape', slashescape)  # --- processing  stream = [b'\x80abc']  lines = [] for line in stream:     lines.append(line.decode('utf-8', 'slashescape')) 
vote vote


In Python 3, the default encoding is "utf-8", so you can directly use:


which is equivalent to


On the other hand, in Python 2, encoding defaults to the default string encoding. Thus, you should use:


where encoding is the encoding you want.

Note: support for keyword arguments was added in Python 2.7.

Top 3 video Explaining python - Convert bytes to a string