Introduction
Various string constant are defined in Python String module. Predefined string constants can be used in common scenarios. To use these constant do not forget to import
import string
String Constants
Common string constant defined in String module are
- string.ascii_letters : Concatenation of the ascii_lowercase and ascii_uppercase constants.
- string.ascii_lowercase : Lowercase letters ‘abcdefghijklmnopqrstuvwxyz’.
- string.ascii_uppercase : Uppercase letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.
- string.digits: String ‘0123456789’.
- string.hexdigits : String ‘0123456789abcdefABCDEF’.
- string.octdigits : String ‘01234567’.
- string.punctuation : String of ASCII characters which are punctuation characters.
- string.whitespace : String containing all ASCII characters that are whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
- string.printable : String of ASCII characters which are printable. This is a combination of digits, ascii_letters, punctuation, and whitespace.
Methods for Constants
String module has predefined methods which operate on above constant. Common methods are
- str.isalnum() : Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise.
- str.isalpha() : Return True if all characters in the string are alphabetic and there is at least one character, False otherwise.
- str.isascii() : Return True if the string is empty or all characters in the string are ASCII, False otherwise.
- str.isdecimal() : Return True if all characters in the string are decimal characters and there is at least one character, False otherwise.
- str.isdigit() : Return True if all characters in the string are digits and there is at least one character, False otherwise.
- str.islower() : Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.
- str.isnumeric() : Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise.
- str.isspace() : Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.
- str.isupper() : Return True if all cased characters in the string are uppercase, False otherwise.
Example
# Example showing usage of above methods and constants import string # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_letters) # 0123456789 print(string.digits) # 0123456789abcdefABCDEF print(string.hexdigits) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ print(string.punctuation) # String testing methods print('123A'.isalnum()) print('ABC'.isalpha()) print('123'.isnumeric()) print('ABC'.isupper())