This always confuses me every single time. I remember it by doing the opposite of what I intuitively think it should be. Perhaps I'm the only one?
bytes.decode - encodes the bytes as UTF-8
str.encode - decodes "removes" the UTF-8 encoding
There is also the abbreviation BADTIE: Bytes Are Decoded, Text Is Encoded. To help to remember it.
python - Encode byte string in utf8 - Stack Overflow
How to convert a string to utf-8 in Python - Stack Overflow
Python: Convert utf-8 string to byte string - Stack Overflow
python how to read bytes type data from file and convert it to utf-8? - Stack Overflow
In Python 2
>>> plain_string = "Hi!"
>>> unicode_string = u"Hi!"
>>> type(plain_string), type(unicode_string)
(<type 'str'>, <type 'unicode'>)
^ This is the difference between a byte string (plain_string) and a unicode string.
>>> s = "Hello!"
>>> u = unicode(s, "utf-8")
^ Converting to unicode and specifying the encoding.
In Python 3
All strings are unicode. The unicode function does not exist anymore. See answer from @Noumenon
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:
stringnamehere.decode('utf-8', 'ignore')
>>> x = "\x61\x62\x63"
>>> x
'abc'
>>> bytes(x, 'utf-8')
b'abc'
>>> str(bytes(x, 'utf-8'))[2:-1]
'abc'
Even though, I would not recommend to use eval in production, you could do the following:
import ast
x = r"\x61\x62\x63"
code = 'b"{0}"'.format(x)
b = ast.literal_eval(code)
b.decode('utf-8')
Edit:
IIRC, the format string came with a later python version, so use
'b"{0}".format(x)'.
Edit: Added comment by Mark Tolonen.
Decode the bytes object to produce a string:
>>> b"abcde".decode("utf-8")
'abcde'
The above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!
Decode the byte string and turn it in to a character (Unicode) string.
Python 3:
encoding = 'utf-8'
b'hello'.decode(encoding)
or
str(b'hello', encoding)
Python 2:
encoding = 'utf-8'
'hello'.decode(encoding)
or
unicode('hello', encoding)
Hi! So I'm trying to decode some utf-8 strings in Python. However some bring up an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 3: invalid start byte or something along the lines of that. Here's the function: def b_numstring(f):
name_len = int.from_bytes(f.read(4), byteorder='big')
string = f.read(name_len).decode('utf-8')
return string Any help would be appreciated. Thanks!