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?
(1) This will give you all caps and numbers:
(2) If you later want to include lowercase letters in your key, then this will also work:
For those of you who enjoy functional python:
It generates an indefinite [infinite] iterator, of joined random sequences, by first generating an indefinite sequence of randomly selected symbol from the giving pool, then breaking this sequence into length parts which is then joined, it should work with any sequence that supports getitem, by default it simply generates a random sequence of alpha numeric letters, though you can easily modify to generate other things:
for example to generate random tuples of digits:
if you don't want to use next for generation you can simply make it callable:
if you want to generate the sequence on the fly simply set join to identity.
As others have mentioned if you need more security then set the appropriate select function:
the default selector is
choice
which may select the same symbol multiple times for each chunk, if instead you'd want the same member selected at most once for each chunk then, one possible usage:we use
sample
as our selector, to do the complete selection, so the chunks are actually length 1, and to join we simply callnext
which fetches the next completely generated chunk, granted this example seems a bit cumbersome and it is ...A simpler, faster but slightly less random way is to use
random.sample
instead of choosing each letter separately, If n-repetitions are allowed, enlarge your random basis by n times e.g.Note: random.sample prevents character reuse, multiplying the size of the character set makes multiple repetitions possible, but they are still less likely then they are in a pure random choice. If we go for a string of length 6, and we pick 'X' as the first character, in the choice example, the odds of getting 'X' for the second character are the same as the odds of getting 'X' as the first character. In the random.sample implementation, the odds of getting 'X' as any subsequent character are only 6/7 the chance of getting it as the first character
A simple one:
From Python 3.6 on you should use the
secrets
module if you need it to be cryptographically secure instead of therandom
module (otherwise this answer is identical to the one of @Ignacio Vazquez-Abrams):One additional note: a list-comprehension is faster in the case of
str.join
than using a generator expression!