Sometimes, we want to generate a random string with upper case letters and digits with Python.
In this article, we’ll look at how to generate a random string with upper case letters and digits with Python.
How to generate a random string with upper case letters and digits with Python?
To generate a random string with upper case letters and digits with Python, we can use the random.choices
method.
For instance, we write:
import random
import string
N = 10
gen = ''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
print(gen)
to generate a 10 character random string.
We call join
on an empty string with the randomly generated characters.
We generate 10 random characters with random.choices(string.ascii_uppercase + string.digits, k=N)
.
string.ascii_uppercase + string.digits
will generate numbers and letter characters.
k
is the number of characters to generate.
And an array characters is returned.
Therefore, gen
should be something like 'M5HHZYW06X'
.
random.choices
is available since Python 3.6.
Conclusion
To generate a random string with upper case letters and digits with Python, we can use the random.choices
method.