hashlib.md5()TypeError:Unicode散列之前必须对Unicode对象进行编码 [英] hashlib.md5() TypeError: Unicode-objects must be encoded before hashing

查看:778
本文介绍了hashlib.md5()TypeError:Unicode散列之前必须对Unicode对象进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 >>> import hashlib 
>>> a = hashlib.md5()
>>> a.update('hi')
追溯(最近的最后一次呼叫):
文件< pyshell#22>,第1行,< module>
a.update('hi')
TypeError:Unicode对象必须在散列之前编码
>>> a.digest()
b'\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec (a)现在被认为是编码?



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

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

追溯(最近的最后一次呼叫):
文件C:/ Users / User / Desktop / Logger / Encoding practice.py,第3行,
a.update('hi')
TypeError:Unicode对象必须在散列之前编码



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



谢谢。

解决方案

由于你是编码简单的字符串,我推断你正在运行Python 3,其中所有的字符串都是unicode对象,你有两个选项:


  1. 提供字符串的编码,例如:没有人检查.encode('utf-8' )

  2. 使用二进制字符串,如手册中所示:

     code> m.update(b没有人检查)
    m.update(b垃圾重复)


shell脚本中不同行为的原因是脚本停止错误,而在shell中,最后一行是单独的命令,但仍然没有做你想要的,因为以前的错误。


I am new to coding and have ran into a problem trying to encode a string.

>>> 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~'

Is (a) now considered to be encoded?

Second question: When I run the same code above in a script I get this error:

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

Traceback (most recent call last): File "C:/Users/User/Desktop/Logger/Encoding practice.py", line 3, in a.update('hi') TypeError: Unicode-objects must be encoded before hashing

Why is the code working in the shell and not the script? I am working with Windows and Python 3.4

Thanks.

解决方案

Since you are encoding simple strings I deduce that you are running Python 3 where all strings are unicode objects, you have two options:

  1. Provide an encoding for the strings, e.g.: "Nobody inspects".encode('utf-8')
  2. Use binary strings as shown in the manuals:

    m.update(b"Nobody inspects")
    m.update(b" the spammish repetition")
    

The reason for the differing behaviour in the script to the shell is that the script stops on the error whereas in the shell the last line is a separate command but still not doing what you wish it to because of the previous error.

这篇关于hashlib.md5()TypeError:Unicode散列之前必须对Unicode对象进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆