How do I convert a Python 3 byte-string variable into a regular string? [duplicate]
I have read in an XML email attachment with
bytes_string=part.get_payload(decode=False)
The payload comes in as a byte string, as my variable name suggests.
I am trying to use the recommended Python 3 approach to turn this string into a usable string that I can manipulate.
The example shows:
str(b'abc','utf-8')
How can I apply the b
(bytes) keyword argument to my variable bytes_string
and use the recommended approach?
The way I tried doesn't work:
str(bbytes_string, 'utf-8')
Solution 1:
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
Solution 2:
Call decode()
on a bytes
instance to get the text which it encodes.
str = bytes.decode()