如何使用hashlib模块修复Unicode编码错误?

时间:2011-07-13 17:40:31

标签: python unicode hashlib

多次搜索后,我无法确定如何避免错误说明:“使用此代码时,必须在散列之前对Unicode对象进行编码”:

    pwdinput = input("Now enter a password:")
    pwd = hashlib.sha1()
    pwd.update(pwdinput)
    pwd = pwd.hexdigest()

如何通过该错误?你如何编码Unicode对象?

1 个答案:

答案 0 :(得分:48)

pwdinput = input("Now enter a password:").encode('utf-8') # or whatever encoding you wish to use

假设您正在使用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.encode