我在rlp.py中有以下代码段:
def encode(obj):
if isinstance(obj, str):
if len(obj) == 1 and chr(obj) < 128:
return obj
为什么不起作用?
import rlp as r
r.encode('\x0f')
给我:
Traceback (most recent call last):
if len(obj) == 1 and chr(obj) < 128:
TypeError: an integer is required (got type str)
我没有得到b'\ x0f'和'\ x0f'和b'\ xf'和'\ xf'之间的区别
谢谢。
答案 0 :(得分:0)
Thomas Hilberts Comment正确指出,正确的代码是:
def encode(obj):
if isinstance(obj, str):
if len(obj) == 1 and ord(obj) < 128:
return obj
现在可以了。
答案 1 :(得分:0)
如果要获取单字符字符串obj
的整数unicode值,则应使用ord(obj)
而不是chr(obj)
。
b'test'
和'test'
之间的区别在于数据类型。第一个是字节对象,其中b''
文字中的每个字符恰好对应于字节对象中的一个字节(因此,文字中仅允许使用ASCII字符)。第二个是unicode字符串。