string
moduleThe string
module in Python is a collection of different constants.
ascii_letters
constantThe 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
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.
import stringascii_letters_output = string.ascii_lettersprint("string.ascii_letters = '%s'" % (ascii_letters_output))
Line 1: We import the string
module.
Line 3: We store the output of string.ascii_letters
in the ascii_letters_output
variable.
Line 5: We print the ascii_letters_output
variable.
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)))
Line 1: We import the string
module.
Lines 3–9: We define a function called is_ascii_letters_only
that 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_1
that contains only ASCII letters.
Line 12: We invoke the is_ascii_letters_only
function by passing str_to_check_1
as the parameter.
Line 14: We define a string called str_to_check_2
that contains digits and ASCII letters.
Line 15: The is_ascii_letters_only
function is invoked passing str_to_check_2
as the parameter.