String Manipulation
upper() and lower() are string methods that make a changed copy of a string. upper() turns every letter into a capital letter, and lower() turns every letter into a small letter.
You must put the brackets after the method name, because the brackets are what tell Python to carry out the method now. Writing sport.upper with no brackets does not convert anything.
Digits, spaces and punctuation are not letters, so they are left exactly as they are. A phrase keeps its spaces and its numbers in the same places, whichever method you use.
| Expression | Result |
|---|---|
sport (where sport is "Match 3 Goals") | Match 3 Goals |
sport.upper() | MATCH 3 GOALS |
sport.lower() | match 3 goals |
Both methods return a new string. The string stored in the variable is not edited in place, so if you want to keep the converted version you must store it, for example code = badge.upper() leaves the original text in badge and puts the capitalised version into code.
sport = "Match 3 Goals"
print(sport.upper())
print(sport.lower())
print(sport)Output:
MATCH 3 GOALS
match 3 goals
Match 3 Goals
Two strings only match if every character matches, and a capital letter is a different character from the same small letter. To make a case-insensitive comparison, convert the input and the stored answer to the same case with lower() before using ==. A user can then type an answer in capitals, small letters or a mixture and still be marked correct.
planet = "Jupiter"
guess = input("Name the largest planet: ")
if guess.lower() == planet.lower():
print("Correct")
else:
print("Not quite")Output when the user types JuPiTeR:
Name the largest planet: JuPiTeR
Correct OCR GCSE Computer Science · String Manipulation