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?
The
random.choice
function picks a random entry in a list. You also create a list so that you can append the character in thefor
statement. At the end str is ['t', 'm', '2', 'J', 'U', 'Q', '0', '4', 'C', 'K'], but thestr = "".join(str)
takes care of that, leaving you with'tm2JUQ04CK'
.Hope this helps!
If you need a random string rather than a pseudo random one, you should use
os.urandom
as the sourceI thought no one had answered this yet lol! But hey, here's my own go at it:
This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:
This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
Using
random.SystemRandom()
instead of just random uses /dev/urandom on *nix machines andCryptGenRandom()
in Windows. These are cryptographically secure PRNGs. Usingrandom.choice
instead ofrandom.SystemRandom().choice
in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.If you're using python3.6 or above, you can use the new secrets module.
The module docs also discuss convenient ways to generate secure tokens and best practices.
A faster, easier and more flexible way to do this is to use the
strgen
module (pip install StringGenerator
).Generate a 6-character random string with upper case letters and digits:
Get a unique list:
Guarantee one "special" character in the string:
A random HTML color:
etc.
We need to be aware that this:
might not have a digit (or uppercase character) in it.
strgen
is faster in developer-time than any of the above solutions. The solution from Ignacio is the fastest run-time performing and is the right answer using the Python Standard Library. But you will hardly ever use it in that form. You will want to use SystemRandom (or fallback if not available), make sure required character sets are represented, use unicode (or not), make sure successive invocations produce a unique string, use a subset of one of the string module character classes, etc. This all requires lots more code than in the answers provided. The various attempts to generalize a solution all have limitations that strgen solves with greater brevity and expressive power using a simple template language.It's on PyPI:
Disclosure: I'm the author of the strgen module.
the following logic still generates 6 character random sample
No need to multiply by 6