Acfe 发表于 2017-4-25 11:55:19

python bytes and string 编码

http://linchunai1212.blog.163.com/blog/static/35112143201110213411104/

在Python中,bytes和string是不同的东西。由一系列不可改变的Unicode字符组成的叫string。而一系列不可改变的介于0-255之间的数字被称为bytes对象。

来看示例:

>>> by = b'abcd\x65' #使用b''的格式定义bytes对象。每一个byte可以是一个ASCII字符或者十六进制数从\x00到\xff。 >>> by b'abcde' >>> type(by)>>> len(by)    #和list和string一样,可以使用内置的len()函数计算bytes对象的长度。 5 >>> by += b'\xff'#和list和string一样,可以使用+操作符连接两个bytes对象。 >>> by b'abcde\xff' >>> len(by) 6 >>> by    #可以使用索引来访问bytes对象中的某一个byte 97 >>> by 101 >>> by = 111   #bytes对象是不可改变的,不能对其赋值。 Traceback (most recent call last):   File "", line 1, inTypeError: 'bytes' object does not support item assignment
虽然我们不能对bytes对象直接赋值,但是我们可以将bytes转换为一个bytearray对象,bytearray对象是可以被修改的。

>>> barr = bytearray(by) >>> barr bytearray(b'abcde\xff') >>> barr = 120 >>> barr bytearray(b'xbcde\xff')
bytes对象和string是不可以混在一起的。

>>> 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'
页: [1]
查看完整版本: python bytes and string 编码