Generate a custom formated string with python

人走茶凉 提交于 2019-12-13 08:35:26

问题


I have a Javascript code that generates a string (similar to uuid) string

Here it is the js code:

var t = "xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxx"
  , i = (new Date).getTime();
return e = t.replace(/[x]/g, function() {
    var e = (i + 16 * Math.random()) % 16 | 0;
    return i = Math.floor(i / 16),
    e.toString(16)
})

How can I generate this string with python?


回答1:


Using regular expression substitution and the new secrets module of Python 3.6 - this is not equivalent to the JavaScript code because this Python code is cryptographically secure and it generates less collisions / repeatable sequences.

The secrets documentation says:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

>>> import re
>>> from secrets import choice
>>> re.sub('x', 
           lambda m: choice('0123456789abdef'), 
           'xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxx')
'5baf40e2-13ef-4692-8e33-507b-40fb84ff'

You'd want this for your IDs to be truly as unique as possible, instead of the Mersenne Twister MT19937 -using random which actually is built to specifically yield a repeatable sequence of numbers.

For Python <3.6 you can do

try:
    from secrets import choice
except ImportError:
    choice = random.SystemRandom().choice



回答2:


Python provides UUID generation by default:

>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'



回答3:


So basically you want some random hex digits:

from random import randint
'-'.join(''.join('{:x}'.format(randint(0, 15)) for _ in range(y)) for y in [10, 4, 4, 4, 10])

Where 10, 4, 4, 4, 10 are lengths of each segment in your format string. You may want to add a seed, but basically this does what your JS code does, producing strings like 'f693a7aef0-9528-5f38-7be5-9c1dba44b9'.



来源:https://stackoverflow.com/questions/45670876/generate-a-custom-formated-string-with-python

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