How to generate a random string in Python

Python is a ​powerful language that allows programmers to perform various tasks using built-in libraries. A random string, for example, can be generated using the built-in libraries. Two libraries are imported for this:

import string
import random

Using this random module, different random strings can be generated.

svg viewer

random.choice() is used to generate strings in which characters may repeat, while random.sample() is used for non-repeating characters.

Method Description
string.ascii_uppercase Returns a string with uppercase characters
string.ascii_lowercase Returns a string with lowercase characters
string.ascii_letters Returns a string with both lowercase and uppercase characters
string.digits Returns a string with numeric characters
string.punctuation Returns a string with punctuation characters

Code

import random
import string
# printing lowercase
letters = string.ascii_lowercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing uppercase
letters = string.ascii_uppercase
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing letters
letters = string.ascii_letters
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing digits
letters = string.digits
print ( ''.join(random.choice(letters) for i in range(10)) )
# printing punctuation
letters = string.punctuation
print ( ''.join(random.choice(letters) for i in range(10)) )
Copyright ©2024 Educative, Inc. All rights reserved