PYTHON3(而不是PYTHON2)类型错误:Won';t隐式地将Unicode转换为字节;use.encode()
我有一个功能,可以和python2完美配合PYTHON3(而不是PYTHON2)类型错误:Won';t隐式地将Unicode转换为字节;use.encode(),unicode,transactions,byte,python-3.5,encode,Unicode,Transactions,Byte,Python 3.5,Encode,我有一个功能,可以和python2完美配合 def writeCache(env, cache): with env.begin(write=True) as txn: for k, v in cache.items(): txn.put(k, v) 但是,当我使用python3.5.2执行它时,它返回以下错误: txn.put(k, v) TypeError: Won't implicitly convert Unic
def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cache.items():
txn.put(k, v)
但是,当我使用python3.5.2执行它时,它返回以下错误:
txn.put(k, v)
TypeError: Won't implicitly convert Unicode to bytes; use .encode()
首先,尝试解决以下问题:
def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cache.items():
k.encode()
有效,但不包括变量v
def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cache.items():
k.encode()
v.encode()
我得到以下信息:
AttributeError: 'bytes' object has no attribute 'encode'
这与
v.encode()
有关。您并没有提供太多信息,但这是我最好的猜测:
for k, v in cache.items():
txn.put(k.encode(), v)
从标题中的TypeError判断,txn.put()
方法希望有字节,但至少有一个参数是(unicode)字符串
v
显然已经是一个bytes对象(因此是AttributeError),因此不再需要对其进行编码。
但是如果k.encode()
起作用,那么它很可能是有问题的(unicode)字符串,对它进行编码应该可以解决问题
请注意,默认情况下,str.encode()
使用'utf-8'
。
不清楚Python 2中是否使用了相同的默认值,其中转换是隐式完成的。
我想这取决于您正在使用的库(即txn.put()
的源库)
这对我很有用
txn.put(str(k).encode(), str(v).encode())