如何使用 hashlib 模块修复 Unicode 编码错误?
经过多次搜索后,我无法确定如何避免出现错误:使用此代码时“必须在散列之前对 Unicode 对象进行编码”:
pwdinput = input("Now enter a password:")
pwd = hashlib.sha1()
pwd.update(pwdinput)
pwd = pwd.hexdigest()
如何克服该错误?如何对 Unicode 对象进行编码?
After multiple searches I have not been able to determine how to avoid an error stating: "Unicode-objects must be encoded before hashing" when using this code:
pwdinput = input("Now enter a password:")
pwd = hashlib.sha1()
pwd.update(pwdinput)
pwd = pwd.hexdigest()
How can I get past that error? How do you encode Unicode-objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您使用的是 Python 3,这会将
input()
返回的 Unicode 字符串转换为以 UTF-8 或您希望使用的任何编码编码的bytes
对象。以前版本的 Python 也有它,但它们对 Unicode 与非 Unicode 字符串的处理有点混乱,而 Python 3 在 Unicode 字符串 (str
) 和不可变序列之间有明确的区别。可能表示也可能不表示 ASCII 字符的字节 (bytes
)。http://docs.python.org/library/stdtypes.html#str.encode
http://docs.python.org/py3k/library/stdtypes.html #str.编码
Assuming you're using Python 3, this will convert the Unicode string returned by
input()
into abytes
object encoded in UTF-8, or whatever encoding you wish to use. Previous versions of Python do have it as well, but their handling of Unicode vs. non-Unicode strings was a bit messy, whereas Python 3 has an explicit distinction between Unicode strings (str
) and immutable sequences of bytes that may or may not represent ASCII characters (bytes
).http://docs.python.org/library/stdtypes.html#str.encode
http://docs.python.org/py3k/library/stdtypes.html#str.encode