Categories
Python Answers

How to generate a random string with upper case letters and digits with Python?

Spread the love

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 string join method with random.choices and string.ascii_uppercase and string.digits.

For instance, we write:

import string
import random

N = 10
s = ''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
print(s)

We call random.choices to generate a random string of characters with upper case and digits as specified by string.ascii_uppercase + string.digits.

k is the number of characters in the string which is N.

We call ''.join to combine the list of chosen characters into a string.

Therefore, s is 'LUG43QPVCR'.

Conclusion

To generate a random string with upper case letters and digits with Python, we can use the string join method with random.choices and string.ascii_uppercase and string.digits.

Leave a Reply

Your email address will not be published. Required fields are marked *