EN
Python - generate random string of size n characters
0
points
In this article, we would like to show you how to generate a random string of size n characters in Python.
Quick solution:
import string
from random import choice
N = 10
group = string.ascii_letters + string.digits
print("".join(choice(group) for i in range(N))) # 2C9foB1rbe
Practical example
In this example, we generate a random string consisting of letters (uppercase & lowercase) and digits.
import string
from random import choice
N = 10
group = string.ascii_letters + string.digits
print("".join(choice(group) for i in range(N))) # 7ZTmrwjEwV
Output:
7ZTmrwjEwV
Explanation
In this section, we want to explain step by step how to generate random strings in Python.
- Choose from which group of characters you want to generate the random string. You can choose the group from the Character groups section below. Join them using
+operator. - Use
choice()function fromrandommodule with all the character groups. - Repeat character selection specified number of times (
N) usingforloop. - Join all characters to the empty string (
"") usingjoin()method.
Character groups
You can choose the character groups from which you would like to get the characters.
string.ascii_lettersstring.ascii_lowercasestring.ascii_uppercasestring.lettersstring.lowercasestring.uppercasestring.digitsstring.hexdigitsstring.octdigitsstring.punctuationstring.printablestring.whitespace
Note:
You can choose multiple groups using
+operator.