Python

Python String Constants

A constant is used to define a fixed value in a variable that cannot be modified anywhere in the code following declaration. The Python string module contains some built-in string constants that can be used for various purposes. You can also define a custom string constant in Python. Custom string constant declaration is different in Python than in other standard programming languages, such as c++, Java, etc. This article covers some uses of built-in string constants of the Python string module.

String Constants in Python

The string module of python contains nine string constants. The values of these string constants are described in the table below.

Constant Name Value
ascii_lowercase ‘abcdefghijklmnopqrstuvwxyz’
ascii_uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
ascii_letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’
digits ‘0123456789’
hexdigits ‘0123456789abcdefABCDEF’
octdigits ‘01234567’
punctuation !”#$%&'()*+,-./:;<=>?@[\]^_`{|}~
whitespace Includes the characters space, tab, linefeed, return, formfeed, and vertical tab
printable Includes the values of digits, ascii_letters, punctuation, and whitespace

These built-in string constants are used for validating data. The next section of this article covers the uses of some of the string constants mentioned above.

Example 1: Use of ascii_lowercase Constant

The following script will take any string data from the user and store it in the variable stringVal. The error variable is set initially to False. If any uppercase letter exists in the stringVal variable, then the error variable will be set to True. After checking all characters of stringVal, if the value of error remains False, then a success message will be printed. Otherwise, an error message will be printed.

#!/usr/bin/env python3

# Import string module
import string

# Take any string data
stringVal = input("Enter any text: ")

# Inilialize error variable
error = False

# Iterate the loop to check any uppercase letter exists or not
for character in stringVal:  
     if character not in string.ascii_lowercase:
         error = True
         
# Print message based on the value of error  
if error == True :
    # Print error message
    print("All characters are not in lowercase")
else:
    # Print success message
    print("Text in correct format")

Output

The script is executed twice. The first input value is invalid, and the second input value is valid, as seen in the image below:

Example 2: Use of string.digits Constant

The following script checks whether the input text contains all number of characters by using the string.digits constant, as in the previous example. If the input value is valid, then the string value will be converted into an integer by using the int() method. Next, it will check whether the input value is a leap year.

# Import string module
import string

# Take any string data
year = input("Enter a year: ")

# Inilialize error variable
error = False


# Iterate the loop to check any uppercase letter exists or not
for character in year:  
     if character not in string.digits:
         error = True
         
 
if error == True :
    print("Invalid year value")
else:
    # Check the year is leap year or not
    year = int(year)  
    if (year % 4) == 0:  
       if (year % 100) == 0:  
           if (year % 400) == 0:  
               leapYear = True  
           else:
               leapYear = False
       else:
            leapYear = True
    else:
        leapYear = False
           
    if leapYear == True:    
        print("%d is a leap year" %year)    
    else:
        print("%d is not a leap year" %year)

Output

The script is executed twice. 2000 is taken as the first input and is a leap year, and 2010 is taken as the second input and is not a leap year, as seem in the image below:

Example 3: Use of Multiple String Constants

The following script shows use of the string.digits and string.punctuation constants for the first input text and the string.ascii_lowercase and string.punctuation constants for the second input.  The first input will take any phone number as the input, which can contain digits, the ‘+’ symbol, and the ‘-‘ symbol. The first input will take any email address as the input, which can contain any small letters, the ‘@’ symbol, and the ‘.’ symbol. If the value of the error variable remains False after checking both input texts, then it will print a success message. Otherwise, it will print the error message.

#!/usr/bin/env python3

# Import string module
import string

# Take any string data
phone = input("Enter your phone number: ")
email = input("Enter your email: ")


# Inilialize error variable
error = False

# Iterate the loop to check the phone number is valid or not
for character in phone:  
     if character not in (string.digits + string.punctuation):
         error = True
         
         
# Iterate the loop to check the email is valid or not
for character in email:  
     if character not in (string.ascii_lowercase + string.punctuation):
         error = True    
         
# Print message based on the value of error  
if error == True :
    print("Phone number or email is invalid")
else:
    print("Phone and email are in correct format")

Output

The script is executed twice. A valid phone and an invalid email address are given in the first execution and a valid phone and a valid email address are given in the second execution, as seen in the image below:

Conclusion

The uses of the three main built-in string constants of Python were explained in this article. Hopefully, reading this article should help Python users better understand how to use string constants in Python.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.