使用 python 生成自定义格式的字符串

Generate a custom formated string with python

我有一个Javascript代码生成一个字符串(类似于uuid)string

这是js代码:

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)
})

如何用 python 生成这个字符串?

Python默认提供UUID代:

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

所以基本上你想要一些随机的十六进制数字:

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

其中 10、4、4、4、10 是格式字符串中每个段的长度。您可能想要添加一个种子,但基本上这会执行您的 JS 代码所做的事情,生成类似于 'f693a7aef0-9528-5f38-7be5-9c1dba44b9'.

的字符串

使用正则表达式替换和 Python 3.6 的新 secrets 模块 - 这不等同于 JavaScript 代码,因为 这个 Python code 是加密安全的,它产生的冲突/可重复序列更少。

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'

您希望您的 ID 尽可能真正独一无二,而不是 Mersenne Twister MT19937 - 使用 random 实际上是专门为生成 可重复的 数字序列。

对于Python<3.6你可以做到

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