I want to generate a string of size N.
It should be made up of numbers and uppercase English letters such as:
- 6U1S75
- 4Z4UKK
- U911K4
How can I achieve this in a pythonic way?
I want to generate a string of size N.
It should be made up of numbers and uppercase English letters such as:
How can I achieve this in a pythonic way?
I found this to be simpler and cleaner.
Just change the 64 to vary the length, vary the CharacterPool to do alpha only alpha numeric or numeric only or strange characters or whatever you want.
Simply use Python's builtin uuid:
If UUIDs are okay for your purposes, use the built-in uuid package.
One Line Solution:
import uuid; uuid.uuid4().hex.upper()[0:6]
In Depth Version:
Example:
If you need exactly your format (for example, "6U1S75"), you can do it like this:
This method is slightly faster, and slightly more annoying, than the random.choice() method Ignacio posted.
It takes advantage of the nature of pseudo-random algorithms, and banks on bitwise and and shift being faster than generating a new random number for each character.
...create a generator that takes out 5 bit numbers at a time 0..31 until none left
...join() the results of the generator on a random number with the right bits
With Timeit, for 32-character strings, the timing was:
...but for 64 character strings, randbits loses out ;)
I would probably never use this approach in production code unless I really disliked my co-workers.
edit: updated to suit the question (uppercase and digits only), and use bitwise operators & and >> instead of % and //
I'd do it this way:
Or just:
Answer in one line:
or even shorter starting with Python 3.6 using
random.choices()
:A cryptographically more secure version; see https://stackoverflow.com/a/23728630/2213647:
In details, with a clean function for further reuse:
How does it work ?
We import
string
, a module that contains sequences of common ASCII characters, andrandom
, a module that deals with random generation.string.ascii_uppercase + string.digits
just concatenates the list of characters representing uppercase ASCII chars and digits:Then we use a list comprehension to create a list of 'n' elements:
In the example above, we use
[
to create the list, but we don't in theid_generator
function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).Instead of asking to create 'n' times the string
elem
, we will ask Python to create 'n' times a random character, picked from a sequence of characters:Therefore
random.choice(chars) for _ in range(size)
really is creating a sequence ofsize
characters. Characters that are randomly picked fromchars
:Then we just join them with an empty string so the sequence becomes a string:
lowercase_str
is a random value like'cea8b32e00934aaea8c005a35d85a5c0'
uppercase_str
is'CEA8B32E00934AAEA8C005A35D85A5C0'