赞
踩
- # bytes object
- b = b"example"
-
- # str object
- s = "example"
-
- # str to bytes
- bytes(s, encoding = "utf8")
-
- # bytes to str
- str(b, encoding = "utf-8")
-
- # an alternative method
- # str to bytes
- str.encode(s)
-
-
- bytes.decode(b)
- base_str = "我已经将我的狗狗送人了"
- print(type(base_str))
- bytes_utf_8 = base_str.encode(encoding="utf-8")
- print(bytes_utf_8)
- bytes_gb2312 = base_str.encode(encoding="gb2312")
- print(bytes_gb2312)
- str_from_utf_8 = bytes_utf_8.decode(encoding="utf-8")
- print(str_from_utf_8)s
- str_from_gb2312 = bytes_gb2312.decode(encoding="gb2312")
- print(str_from_gb2312)
- 1 # bytes 与 int
- 2 b=b'\x01\x02'
- 3 num=int.from_bytes(b,'little')
- 4 print('bytes转int:',num)
- 5
- 6 b1=num.to_bytes(2,'little')
- 7 print('int转bytes:',b1)
- 8
- 9 #bytes 与十六进制string
- 10 hs=''.join(['%02X' %x for x in b])
- 11 print('bytes转十六进制字符串:',hs)
- 12 bs=bytes.fromhex(hs)
- 13 print('十六进制字符串转bytes:',bs)
- 14 # print(bytes.fromhex(hex(78)[2:]))
- 15
- 16 #int 与 string
- 17 s='abcd'
- 18 num=int(s,16)
- 19 print('字符串转int:',num)
- 20 print('int转十六进制字符串:',hex(num))
输出:
bytes转int: 513
int转bytes: b'\x01\x02'
bytes转十六进制字符串: 0102
十六进制字符串转bytes: b'\x01\x02'
字符串转int: 43981
int转十六进制字符串: 0xabcd
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。