What is the ascii_letters constant in Python?
The string module
The string module in Python is a collection of different constants.
The ascii_letters constant
The ascii_letters constant in the string module contains all the English letters from a to z. These letters are in lowercase and uppercase as a single string.
The value of the constant is as follows:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Syntax
string.ascii_letters
Since ascii_letters is a constant, we can access it via the string module.
Let’s look at two code examples that use the ascii_letters constant.
Example 1
import stringascii_letters_output = string.ascii_lettersprint("string.ascii_letters = '%s'" % (ascii_letters_output))
Explanation
-
Line 1: We import the
stringmodule. -
Line 3: We store the output of
string.ascii_lettersin theascii_letters_outputvariable. -
Line 5: We print the
ascii_letters_outputvariable.
Example 2
import stringdef is_ascii_letters_only(str_input):for i in str_input:if i not in string.ascii_letters:return Falsereturn Truestr_to_check_1 = "abjiaosfdgfRFDFD"print("Does %s contain only ascii letters? %s" % (str_to_check_1, is_ascii_letters_only(str_to_check_1)))str_to_check_2 = "abji232daosfdgfRFDFD"print("Does %s contain only ascii letters? %s" % (str_to_check_2, is_ascii_letters_only(str_to_check_2)))
Explanation
-
Line 1: We import the
stringmodule. -
Lines 3–9: We define a function called
is_ascii_letters_onlythat accepts a string as its parameter and checks whether this string contains only ASCII letters. -
Line 11: We define a string called
str_to_check_1that contains only ASCII letters. -
Line 12: We invoke the
is_ascii_letters_onlyfunction by passingstr_to_check_1as the parameter. -
Line 14: We define a string called
str_to_check_2that contains digits and ASCII letters. -
Line 15: The
is_ascii_letters_onlyfunction is invoked passingstr_to_check_2as the parameter.