在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[0] #可以使用索引来访问bytes对象中的某一个byte 97 >>> by[4] 101
>>> by[0] = 111 #bytes对象是不可改变的,不能对其赋值。
Traceback (most recent call last):
File \"\
TypeError: 'bytes' object does not support item assignment
虽然我们不能对bytes对象直接赋值,但是我们可以将bytes转换为一个bytearray对象,bytearray对象是可以被修改的。
>>> barr = bytearray(by)
>>> barr
bytearray(b'abcde\\xff')
>>> barr[0] = 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'
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务