Upper and Lower Case
Programs work with text all the time: names, messages, addresses, everything people type. In this lesson, you'll learn to tidy up text, search in it, take it apart and put it back together.
You know from the lesson on lists that lists have methods, functions that belong to a value and are written after a dot, such as names.append("Tom"). Text has methods too, and plenty of them. Three of them change uppercase and lowercase letters:
city = "new York"
print(city.upper())
print(city.lower())
print(city.capitalize())This prints:
NEW YORK
new york
New yorkupper() turns every letter into uppercase and lower() into lowercase. capitalize() makes the first character of the text uppercase and all the others lowercase, which is why the Y in York became lowercase. Characters that aren't letters, such as spaces and digits, stay as they are.
Now the important part. In the lesson on lists, you saw that a text can't be changed: city[0] = "N" ends with a TypeError. Its methods can't change it either. Instead, each of them returns a new text and leaves the original as it was:
name = "anna"
name.upper()
print(name)This prints:
annaname.upper() returned "ANNA", but nothing stored it, so the new text was lost, like the return value of a function that nobody uses. To keep it, store it in a variable, a new one or the same one, or use it right away:
name = "anna"
loud_name = name.upper()
print(loud_name, name)
name = name.capitalize()
print(name)This prints:
ANNA anna
AnnaLists work the other way round: append() changes the list itself and returns None. With text, what counts is always what the method returns.
Lowercase is handy for comparing. == compares texts exactly, so "Yes" == "yes" is False. When case shouldn't matter, as in what a person typed, turn the text into lowercase before you compare it:
answer = "YES"
if answer.lower() == "yes":
print("Great, let's go!")This prints Great, let's go!, whether the person typed yes, Yes or YES. Here one side is enough, because "yes" is already in lowercase. When you compare two variables, turn both into lowercase: a.lower() == b.lower().
Instructions
- 1
A quiz game asks for the capital of France. The player typed the right city, just in capital letters, but the program prints
Wrong!Change the condition so that it compares both texts in lowercase. The program then printsCorrect!Keep the lineanswer = "PARIS": the exercise also tries other answers in it. - 2
Below the
ifstatement, print the player's answer with its first letter in uppercase and the rest in lowercase, usingcapitalize():Your answer: Paris.