#!/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