Skip to content

Python 字符串转换

单字符

ord(char) 输出asciiord(char) 输出ascii码 chr(64) 输出char

python2 int,str,hex转换

bytes,hex互转

1
2
binascii.hexlify(b"31")="3331"   #bytes转hex字符串 python3、codecs.encode(test_value, 'hex_codec')
binascii.b2a_hex("3331")=b"31" #bytes转str

str bytes 互转

1
2
"123".encode('ascii')=b'123' #str 转bytes  (s.encode('charmap')使用拓展ascii)
b'123'.decode('ascii')='123'  #bytes转str

bytes int 互转

1
2
3
4
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

定义

1
a=b"abc"

取出一个字节自动转为int值

1
2
3
4
In [4]: a[0]
Out[4]: 97
In [5]: type(a[1])
Out[5]: int

不能修改值,需要修改先转成bytearr

bytesarray bytes互转

bytes转bytesarray

1
2
3
4
In [44]: a=b'123'
In [45]: a_arr=bytearray(a)
In [46]: a_arr
Out[46]: bytearray(b'123')

bytesarray转bytes

1
2
In [47]: bytes(a_arr)
Out[47]: b'123'

bytes str互转

str转bytes

1
"str".encode('ascii')
或者
1
2
In [28]: bytes("str",'ascii')
Out[28]: b'str'

bytes转str

1
b.decode('ascii')

str转bytearray

1
In [2]: a=bytearray("123","ascii")

bytes str互转

bytes转hexstr

1
2
In [36]: b.hex()
Out[36]: '737472'

bytesarray转hexstr

1
2
In [41]: a_arr.hex()
Out[41]: '016263'

hexstr转bytes

1
bytes.fromhex(h)

hexstr转bytesarray

1
2
In [38]: bytearray.fromhex(h)
Out[38]: bytearray(b'str')