Generate ID from string in Python

爷,独闯天下 提交于 2019-12-23 09:57:12

问题


I'm struggling a bit to generate ID of type integer for given string in Python.

I thought the built-it hash function is perfect but it appears that the IDs are too long sometimes. It's a problem since I'm limited to 64bits as maximum length.

My code so far: hash(s) % 10000000000. The input string(s) which I can expect will be in range of 12-512 chars long.

Requirements are:

  • integers only
  • generated from provided string
  • ideally up to 10-12 chars long (I'll have ~5 million items only)
  • low probability of collision..?

I would be glad if someone can provide any tips / solutions.


回答1:


I would do something like this:

>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("some string")
>>> str(int(m.hexdigest(), 16))[0:12]
'120665287271'

The idea:

  1. Calculate the hash of a string with MD5 (or SHA-1 or ...) in hexadecimal form (see module hashlib)
  2. Convert the string into an integer and reconvert it to a String with base 10 (there are just digits in the result)
  3. Use the first 12 characters of the string.

If characters a-f are also okay, I would do m.hexdigest()[0:12].



来源:https://stackoverflow.com/questions/22974499/generate-id-from-string-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!