Python:如何将一个字符串散列为8位数字? [英] Python: How to hash a string into 8 digits?

查看:687
本文介绍了Python:如何将一个字符串散列为8位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我可以将一个随机字符串散列为8位数字,而无需自己实施任何算法?谢谢。

解决方案

是的,您可以使用内置的 hashlib 模块或内置的 hash 功能。然后,使用模运算或对整数形式的散列进行字符串切片操作来截掉最后八位数字:

 > >> s ='她在海边销售海贝壳'

>>> #使用hashlib
>>> import hashlib
>>> int(hashlib.sha1(s).hexdigest(),16)%(10 ** 8)
58097614L

>>> #使用hash()
>>> abs(hash(s))%(10 ** 8)
82148974


Is there anyway that I can hash a random string into a 8 digit number without implementing any algorithms myself? Thanks.

解决方案

Yes, you can use the built-in hashlib modules or the built-in hash function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974

这篇关于Python:如何将一个字符串散列为8位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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