Ray*_*ger 113
是的,您可以使用内置的hashlib模块或内置的哈希函数.然后,在整数形式的散列上使用模运算或字符串切片操作来切断最后八位数:
>>> 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
Run Code Online (Sandbox Code Playgroud)
JJC*_*JJC 63
雷蒙德的答案对于python2来说很棒(但是,你不需要abs()也不需要10**8左右的parens).但是,对于python3,有一些重要的警告.首先,您需要确保传递编码的字符串.这些天来,在大多数情况下,回避sha-1并使用像sha-256这样的东西也可能更好.因此,hashlib方法将是:
>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417
Run Code Online (Sandbox Code Playgroud)
如果你想使用hash()函数,重要的警告是,与Python 2.x不同,在Python 3.x中,hash()的结果只在进程内是一致的,而不是在python调用中.看这里:
$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934
Run Code Online (Sandbox Code Playgroud)
这意味着建议使用基于hash()的解决方案,该解决方案可以简化为:
hash(s) % 10**8
只会在给定的脚本运行中返回相同的值:
#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451
Run Code Online (Sandbox Code Playgroud)
因此,根据您的应用程序(在我的应用程序中)是否重要,您可能希望坚持基于hashlib的方法.
小智 12
从 Python 3.10 开始,将字符串哈希为 8 个十六进制数字摘要的另一种快速方法是使用shake.hexdigest(4):
import hashlib
h=hashlib.shake_128(b"my ascii string").hexdigest(4)
#34c0150b
Run Code Online (Sandbox Code Playgroud)
注意 4 而不是 8,因为摘要的长度是作为参数给出的数字的两倍。
当然要注意哈希冲突。
小智 9
只是为了完成 JJC 答案,在 python 3.5.3 中,如果您以这种方式使用 hashlib,则行为是正确的:
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -V
Python 3.5.3
Run Code Online (Sandbox Code Playgroud)