2.3. String String

2.3.1. SetUp

>>> import string

2.3.2. Letters

  • string.ascii_lowercase - Lowercase letters

  • string.ascii_uppercase - Uppercase letters

  • string.ascii_letters - Combination of lowercase and uppercase letters

>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

2.3.3. Numbers

  • string.digits - Decimal digits

  • string.hexdigits - Hexadecimal digits

  • string.octdigits - Octal digits

>>> string.digits
'0123456789'
>>>
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>>
>>> string.octdigits
'01234567'

2.3.4. Special Characters

  • string.punctuation - Punctuation characters

  • string.whitespace - Whitespace characters

  • string.printable - Combination of digits, letters, punctuation, and whitespace

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

2.3.5. Use Case - 1

>>> from string import ascii_uppercase
>>>
>>> list(ascii_uppercase)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

2.3.6. Use Case - 2

>>> from string import ascii_uppercase
>>>
>>> data = [1, 2, 3, 4, 5]
>>> columns = list(ascii_uppercase)[:len(data)]
>>>
>>> columns
['A', 'B', 'C', 'D', 'E']
>>>
>>> data
[1, 2, 3, 4, 5]

2.3.7. Use Case - 3

>>> username = 'alice!'
>>>
>>> for char in username:
...     if char in string.punctuation:
...         raise ValueError('Username contains invalid character')
...
Traceback (most recent call last):
ValueError: Username contains invalid character