Contents
Generate Random String with Python
A random string may be required for a system generated strong password, or such another scenarios.
Using random module of Python programming, you can generate such strings of specified length and specified character groups.
To generate a random string of specific length, follow these steps.
Step 1 – Choose Character Group
Choose the character groups from which you would like to pickup the characters. string
class provides following character groups:
- string.ascii_letters
- string.ascii_lowercase
- string.ascii_uppercase
- string.digits
- string.hexdigits
- string.letters
- string.lowercase
- string.octdigits
- string.punctuation
- string.printable
- string.uppercase
- string.whitespace
Step 2 – random.choice()
Use random.choice() function with all the character groups (appended by + operator) passed as argument.
random.choice(string.ascii_uppercase + string.digits)
Run random.choice() picks one of the characters from the given string or characters.
Step 3 – Repeat picking the characters
Repeat this for N times, N being the length of the random string to be generated.
random.choice(string.ascii_uppercase + string.digits) for _ in range(N)
Run Step 4 – Join Characters
Join all these N characters.
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
Run Example – Generate Random String of Specific Length
Let us implement all the afore mentioned steps to generate a random string of specific length.
import random
import string
def randStr(chars = string.ascii_uppercase + string.digits, N=10):
return ''.join(random.choice(chars) for _ in range(N))
# default length(=10) random string
print(randStr())
# random string of length 7
print(randStr(N=7))
# random string with characters picked from ascii_lowercase
print(randStr(chars=string.ascii_lowercase))
# random string with characters picked from 'abcdef123456'
print(randStr(chars='abcdef123456'))
Run 4FH2R5SQ9D
8STJX1L
iihvalhdwc
d35bbbfcea
Related Tutorials
- Python Program to Generate Random Password
- Python Program to Flip a Coin
- PyTorch Create Tensor with Random Values and Specific Shape
- Python Program to Generate a Random Number of Specific Length
- Python Random Module Examples
- Python Numpy – Create Array with Random Values
- Python – Generate a Random Number – Positive or Negative
- Python Program to Generate Random Float