Trusted answers to developer questions

How to generate a random string in Python

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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)) )

RELATED TAGS

python
random string
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?