-
bytes
按索引取值得到的是整数。b'abc'[0] 97
-
str
转bytes
只需要编码一下就行了。反过来就是解码一下。s = '你好' b = bytes(s, 'utf-8') # b'\xe4\xbd\xa0\xe5\xa5\xbd' assert b.decode('utf-8') == s
bytes('hello') TypeError: string argument without an encoding bytes('hello', 'ascii') b'hello' 'hello'.encode() b'hello' bytes('hello', 'utf-16') b'\xff\xfeh\x00e\x00l\x00l\x00o\x00' bytes('hello', 'utf-32') b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00'
-
bytes
和int
列表的转换。list(b'abc') [97, 98, 99] bytes([97, 98, 99]) b'abc' bytes([256]) ValueError: bytes must be in range(0, 256) # 大端序 (2008).to_bytes(length=4, byteorder='big', signed=False) b'\x00\x00\x07\xd8' # 小端序 (2008).to_bytes(length=4, byteorder='little', signed=False) b'\xd8\x07\x00\x00' struct.pack('<I', 2008) b'\xd8\x07\x00\x00' int.from_bytes(b'\x00\x00\x07\xd8', 'big') 2008 int.from_bytes(b'\xd8\x07\x00\x00', 'little') 2008 int.from_bytes(b'abc', 'little') 6513249 int.from_bytes(b'cba', 'big') 6513249
PS:2020/11/02, 字节顺序(大端序、小端序)
-
Python2 字符串
# python2 print(repr('你好')) '\xc4\xe3\xba\xc3' print('\xc4\xe3\xba\xc3') 你好 # python3 print('\xc4\xe3\xba\xc3') 'ÄãºÃ' print('\xc4\xe3\xba\xc3'.encode('latin-1')) b'\xc4\xe3\xba\xc3' print('\xc4\xe3\xba\xc3'.encode('latin-1').decode('gbk')) '你好'
TOC
Python bytes
类型
发布于码厩技术博客的所有文章,除注明转载外,均为作者原创,欢迎转载,但必须注明出处。
尊重他人劳动,共创开源社区!转载请注明以下信息:
转载来源: 码厩技术博客 [https://www.markjour.com]
原文标题:Python <code>bytes</code> 类型
原文地址:/article/20160516-python-bytes.html
尊重他人劳动,共创开源社区!转载请注明以下信息:
转载来源: 码厩技术博客 [https://www.markjour.com]
原文标题:Python <code>bytes</code> 类型
原文地址:/article/20160516-python-bytes.html

如果你有魔法,你可以看到一个评论框~