dorafmon dorafmon - 4 years ago 206
Python Question

Python: How to hash a string into 8 digits?

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

Answer Source

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)

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download