起步
# python2.7
pwd = "xxx" + chr(163) + "fj"
checkcode = hashlib.md5(pwd).hexdigest()
print checkcode # ea25a328180680aab82b2ef8c456b4ce
# python3.6
pwd = "xxx" + chr(163) + "fj"
checkcode = hashlib.md5(pwd.encode("utf-8")).hexdigest()
print(checkcode) # b517e074034d1913b706829a1b9d1b67
checkcode = hashlib.md5(pwd).hexdigest()
TypeError: Unicode-objects must be encoded before hashing
分析
# python2.7
>>> chr(163)
'\xa3'
# python3.6
>>> chr(163)
'\xa3'
# python2.7
>>> bytes(chr(163))
'\xa3'
# python3.6
>>> chr(163).encode()
b'\xc2\xa3'
解决
# python3.6
pwd = "xxx" + chr(163) + "fj"
checkcode = hashlib.md5(pwd.encode("latin1")).hexdigest()
print(checkcode) # ea25a328180680aab82b2ef8c456b4ce
额外
chr(...)
chr(i) -> Unicode character
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.