gpt4 book ai didi

python - hashlib.md5() 类型错误 : Unicode-objects must be encoded before hashing

转载 作者:IT老高 更新时间:2023-10-28 20:51:19 26 4
gpt4 key购买 nike

我是编码新手,在尝试对字符串进行编码时遇到了问题。

>>> import hashlib
>>> a = hashlib.md5()
>>> a.update('hi')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.update('hi')
TypeError: Unicode-objects must be encoded before hashing
>>> a.digest()
b'\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec\xf8B~'

现在是否考虑对 (a) 进行编码?

第二个问题:当我在脚本中运行上面相同的代码时,我得到了这个错误:

import hashlib
a = hashlib.md5()
a.update('hi')
a.digest()

Traceback(最近一次调用最后一次): 文件“C:/Users/User/Desktop/Logger/Encoding practice.py”,第 3 行,在 a.update('嗨')TypeError: Unicode 对象必须在散列之前进行编码

为什么代码在 shell 而不是脚本中运行?我正在使用 Windows 和 Python 3.4

谢谢。

最佳答案

我找到的解决方案是简单地在你正在散列它的行中立即对数据进行编码:

hashlib.sha256("a".encode('utf-8')).hexdigest()

它对我有用,希望对你有帮助!

关于python - hashlib.md5() 类型错误 : Unicode-objects must be encoded before hashing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27519306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com