>>> by
b’abcde\xff’
>>> s = “abcdefg”
>>> by + s
Traceback (most recent call last):
File ““, line 1, in
TypeError: can’t concat bytes to str
但是,bytes和string并不是毫无关系的,bytes对象有一个decode()方法,向该方法传递一个字符编码参数,该方法会返回使用该种编码解码后的字符串。同样的,string有一个encode()方法,完成反向的工作。
>>> string = "深入 Python" >>> len(string) 9 >>> by = string.encode('utf-8') #将字符串编码为UTF8 >>> len(by) 13 >>> by b'\xe6\xb7\xb1\xe5\x85\xa5 Python' >>> by = string.encode('gb18030') #将字符串编码为GB18030 >>> len(by) 11 >>> by b'\xc9\xee\xc8\xeb Python' >>> by.decode('gb18030') #将bytes对象解码 '深入 Python'