我有一个字节代码,我想获得相应字节的序列。例如,代码为65
,序列应为b'A'
。我知道有一种简单的方法可以做到:
b = chr(65).encode()
print(b) # b'A'
但由于在中间转换为字符串,它似乎太慢且过度充电。在Python 3中,有没有一种快速而优雅的方法来做到这一点?
答案 0 :(得分:1)
使用bytes
构造函数:
>>> bytes([65])
b'A'
还有一种to_bytes
方法,如果整数代表多个字节,则最有用,但它也适用于1:
>>> (65).to_bytes(1, 'big') # big or little endian makes no difference for 1
b'A'
另一种方法就是索引:
>>> b'A'[0]
65