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?
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