使用Python 3进行哈希处理:是否需要对每个字符串进行.encode()? [英] Hashing with Python 3: Do I need to .encode() every string?

查看:68
本文介绍了使用Python 3进行哈希处理:是否需要对每个字符串进行.encode()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Python 2迁移到Python 3,想知道是否现在需要对每个字符串文字进行编码,然后才能对其进行哈希处理.示例代码将在Python 2下完美运行:

I'm migrating from Python 2 to Python 3 and wonder if every string literal needs to be encoded now before you can hash it. Example code will run perfectly under Python 2:

import hashlib
string = "robots"
hashlib.md5(string).hexdigest()

但是使用Python 3,它会引发一个 TypeError:Unicode对象必须在散列之前进行编码,因此我必须在每个字符串或字符串后附加一个 .encode().我在这里想念东西吗?

using Python 3 however, it throws a TypeError: Unicode-objects must be encoded before hashing so I have to append an .encode() after each string or am I missing something here?

推荐答案

hashlib

注意:不支持将字符串对象输入到 update()中,因为散列仅适用于字节,而不适用于字符.

Note: Feeding string objects into update() is not supported, as hashes work on bytes, not on characters.

因此,只要您想在Python 3中对 str 对象进行哈希处理,就必须先对其进行编码.

So any time you'd like to hash a str object in Python 3, you have to encode it first.

这篇关于使用Python 3进行哈希处理:是否需要对每个字符串进行.encode()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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