Python 字符串转换
单字符
ord(char) 输出asciiord(char) 输出ascii码
chr(64) 输出char
python2 int,str,hex转换
bytes,hex互转
| binascii.hexlify(b"31")="3331" #bytes转hex字符串 python3、codecs.encode(test_value, 'hex_codec')
binascii.b2a_hex("3331")=b"31" #bytes转str
|
str bytes 互转
| "123".encode('ascii')=b'123' #str 转bytes (s.encode('charmap')使用拓展ascii)
b'123'.decode('ascii')='123' #bytes转str
|
bytes int 互转
| int.from_bytes(b'\x00\x10', byteorder='little') # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) #-1024
123.to_bytes(_bit, byteorder='little')=b'{x00' #int转bytes(_bit位)
|
python3
bytes
定义
取出一个字节自动转为int值
| In [4]: a[0]
Out[4]: 97
In [5]: type(a[1])
Out[5]: int
|
不能修改值,需要修改先转成bytearr
bytesarray bytes互转
bytes转bytesarray
| In [44]: a=b'123'
In [45]: a_arr=bytearray(a)
In [46]: a_arr
Out[46]: bytearray(b'123')
|
bytesarray转bytes
| In [47]: bytes(a_arr)
Out[47]: b'123'
|
bytes str互转
str转bytes
或者
| In [28]: bytes("str",'ascii')
Out[28]: b'str'
|
bytes转str
str转bytearray
| In [2]: a=bytearray("123","ascii")
|
bytes str互转
bytes转hexstr
| In [36]: b.hex()
Out[36]: '737472'
|
bytesarray转hexstr
| In [41]: a_arr.hex()
Out[41]: '016263'
|
hexstr转bytes
hexstr转bytesarray
| In [38]: bytearray.fromhex(h)
Out[38]: bytearray(b'str')
|