Generate a custom formated string with python

2024/10/6 5:54:03

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?

Answer

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
https://en.xdnf.cn/q/118864.html

Related Q&A

PySide-6.6: clicked signal sends extra boolean argument to slot

I just upgraded PySide6 (PySide6==6.6.0 from 6.2.2) and a new behavior is wreaking havoc with my GUI program. Every place where I have a clicked signal, the hooked up slot is receiving an extra bool==F…

SMTPConnectError when using Django

Im using django-registration for handling of users registration. I tried to signup in order to test it, after testing it, I got this errorSMTPConnectError at /accounts/register/Being trying to find a s…

how to have a single search API using path parameters (No form used)

I have been using this view for searching a word as:db refers mongo connection (just for ref)@app.route(/) def index():return render_template(index.html)@app.route(/words-<word>, methods=[GET, PO…

understanding the return type of anonymous function lambda

I am trying to understand how can lambda function be used. def adder_func(a, b):return a + bprint(adder_func(4, 5))# trying with lambda print(list(lambda a, b: a + b))When trying to use lambda as a add…

What is the meaning of Failed building wheel for flask-mysqldb in pip3 install?

I have a MacBook Air with macOs Sonoma 14.0 and when I write in the terminal $ pip3 install flask-mysqldbI get the error:How can I fix this?

How do I install pygame for a new version of idle? (Windows) [duplicate]

This question already has answers here:Error on install Pygame(3.9) install (Win10) [duplicate](1 answer)Unable to install pygame on Python via pip (Windows 10)(6 answers)Closed 3 years ago.I installed…

How to parse a dynamic dom element?

I want to make a parser for scraping price, however I cant find the working method of parsing innerHTMLI dont know why, but selenium (getAttribute(innerHTML)), phantomjs (page.evaluation function(){ret…

Get a string in Shell/Python with subprocess

After this topic Get a string in Shell/Python using sys.argv , I need to change my code, I need to use a subprocess in a main.py with this function :def download_several_apps(self):subproc_two = subpro…

Python Indentation Error when there is no indent error [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.Is it me or the interpreter? I see no indentation error in my cod…

How to mark rgb colors on a colorwheel in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 months ago.Improv…