Python - How to generate a random string

By xngo on June 7, 2019

#!/usr/bin/python3
# Description: Generate random string of specific length.
 
import random
import string
 
def getRandomString(length=8):
 
    input_string = string.ascii_letters + string.digits + string.punctuation
 
    # Use random.choice() to pick random character from input_string.
    random_string = ""
    for i in range(length):
        random_string += random.choice(input_string)
 
    return random_string
 
print(getRandomString())
print(getRandomString(11))
print(getRandomString(17))

Output

$./random-string.py 
%\gjINL[
C!B[W,AcN,)
C7"~N[d)8TX#tPg~J

Reference

  • https://docs.python.org/2/library/string.html#string-constants
  • https://docs.python.org/2/library/random.html#random.choice

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.