Python String Module

Remember – this is GCSE level programming, so go easy on the criticism!

Python 3.x String Constants
I’ve set my students a programming task to create a hangman style game. One of the things we need to do for the game is be able to check that the user’s guess is a valid alphabet character. Let’s explore some of the string constants in the ‘string’ module.

First of all we need to import the string module:

import string

Then we can return various constants from the module:

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

We can seperate that out into lowercase or uppercase letters:

>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

We can also return numbers in various number bases:

>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'

We can also get all the punctuation:

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

So, going back to the hangman game, if we wanted to start checking if the user has entered a valid letter we could utilise the letters constant:

import string
guess = input("Please enter your guess: ")
if guess in string.ascii_letters:
    print("That's a valid guess!")
else:
    print("Your guess must be a letter.")

The following code is the same, but shown with line comments:

# Import the string module
import string
# Define a variable called guess and set it to the input
guess = input("Please enter your guess: ")
# Create an if statement that checks if the value contained in var 'guess' matches 
# any character in the 'string.ascii_letters' constant.
if guess in string.ascii_letters:
    print("That's a valid guess!")
else:
    print("Your guess must be a letter.")