22. Checking Strings

  • We can check strings using the same methods as with numbers
  • A character is simply a string with a length of 1
  • The in operator is a quick way of checking if one string or character is contained within another – useful to check user input against an allowed list of characters or symbols
  • Some operators have interesting results, and work when you least expect them
#Define a string & read in a character
string = "abcdefg"
char = input("Enter a character: ")

#Check if char is in string
if char in string:
    print("The character is in the string!")
else:
    print("The character was not found!")

#More general comparison using IF
if char > "m":
    print("Character is after m in the alphabet")

Tasks

  1. Type in the code above and make sure it works
  2. Modify the program to check if the character entered is in the alphabet (there are two ways to do this using the examples shown)
  3. Save and label your code

Extension Task

The use of the NOT operator can be used as follows. Experiment.

if char not in string:
    print("The character is not in the string!")