Python string digits, ascii_letters, punctuation and printable

Python string module has several attributes, such as digits, ascii_letters. string.digits is a string 0123456789. You don't need to declare a digits string or alphabets string to generate a random string or string whose letters are all uppercase.

import string

print(string.digits)
# 0123456789

print(string.ascii_letters)
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz

print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ

print(string.punctuation)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

print(string.whitespace)
'''


'''

print(string.printable)
'''
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~  

'''

ascii_letters is a sum of ascii_lowercase and ascii_uppercase. whitespace is \t\n\r\v\f. And printable is a sum of

  • digits
  • ascii_letters
  • punctuation
  • whitespace

The following code is an example to generate 8 letter random string using secrets and string module.

import secrets
import string

a = string.digits + string.ascii_letters + string.punctuation
s = ''

for i in range(8):
    s = s + secrets.choice(a)

print(s)  # K^5TXp}<

Python String

Python Tutorial