Python3报错TypeError:Unicode对象哈希前需编码的解决方法
修复Python3中hashlib的Unicode编码错误
这个问题我太熟啦!完全是Python3和Python2在字符串处理逻辑上的差异导致的~
你遇到的错误提示很明确:
TypeError: Unicode-objects must be encoded before hashing
在Python2里,str类型本质就是字节序列,直接传给hashlib.md5()完全没问题;但到了Python3,str是纯Unicode字符串,而哈希函数只能处理字节串,所以必须先把Unicode字符串编码成字节格式才能正常使用。
最简单的修复方式
只需要给你的item_name加上编码方法,把它转换成字节串就行,通用首选utf-8编码:
修改后的代码:
result_file = '/tmp/search_{}.html'.format(hashlib.md5(item_name.encode('utf-8')).hexdigest())
额外兼容小技巧
如果你的item_name有可能是字节串(比如从文件读取的原始数据),可以加个简单判断来兼容两种情况:
# 先统一转换成字节串 if isinstance(item_name, str): item_bytes = item_name.encode('utf-8') else: item_bytes = item_name result_file = '/tmp/search_{}.html'.format(hashlib.md5(item_bytes).hexdigest())
内容的提问来源于stack exchange,提问作者9 conky




