string.ascii_lowercase retunr all the lowercase letter in a single string. I.e., 'abcdefghijklmnopqrstuvwxyz'
random.choice() function choose a single character from a list.
Example 1:
import random
import string
def generateString(stringSize=8):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringSize))
# default length 8
print ("Random String is ", generateString() )
print ("Random String is ", generateString(10) )
print ("Random String is ", generateString(10) )
Example 2: Using user defined string
import random
def generateString(stringSize=8):
"""Generate a random string of fixed length """
letters = 'abcdefghijklmnopqrstuvwxyz'
return ''.join(random.choice(letters) for i in range(stringSize))
# default length 8
print ("Random String is ", generateString() )
print ("Random String is ", generateString(10) )
print ("Random String is ", generateString(10) )
Example 3: Generate random id of length 8
like 'ABCD1234'
import random
def generateString():
"""Generate a random string of fixed length """
letters = 'abcdefghijklmnopqrstuvwxyz'
numbers = '0123456789'
prefix = ''.join(random.choice(letters) for i in range(4))
suffix = ''.join(random.choice(numbers) for i in range(4 ))
return prefix + sufix
# default length 8
print ("Random String is ", generateString() )
Other useful methods:
string.ascii_uppercase: return upper case letter
string.ascii_lowercase: return upper case letter
string.ascii_letters: return mix of upper case letter and lower case
string.digits: return digits letter
string.printable: contains all lower case and upper case letters, digits, and special characters.
string.punctuation: return punctuations