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?
The key to troubleshooting Unicode errors in Python is to know what types you have. Then, try these steps: If some variables are byte sequences instead of Unicode objects, convert them to Unicode objects with decode() / u” before handling them.
To fix UnicodeEncodeError: 'charmap' codec can't encode characters with Python, we can set the encodings argument when we open the file. to call open with the fname file name path and the encoding argument set to utf-8 to open the file at fname as a Unicode encoded file.
hexdigest() : the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.
pwdinput = input("Now enter a password:").encode('utf-8') # or whatever encoding you wish to use
Assuming you're using Python 3, this will convert the Unicode string returned by input()
into a bytes
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With