Trusted answers to developer questions

What is the ascii_letters constant in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 string
ascii_letters_output = string.ascii_letters
print("string.ascii_letters = '%s'" % (ascii_letters_output))

Explanation

  • 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.

Example 2

import string
def is_ascii_letters_only(str_input):
for i in str_input:
if i not in string.ascii_letters:
return False
return True
str_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 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.

RELATED TAGS

python
strings
constant
Did you find this helpful?