Sub topic 6
Changing case
This chapter assumes you know that str methods return new strings, which the earlier chapter on immutability covered. It also assumes you can read basic function calls and if statements. Here you will learn the five case-changing methods, what each one does to the rest of the string, and where they give surprising results.
The five methods
Python has five methods that change letter case. Each one returns a new string, and the original stays the same.
| Method | What it does | Example result for `"hello wORLD"` |
|---|---|---|
| `lower()` | Every cased letter becomes lowercase | `hello world` |
| `upper()` | Every cased letter becomes uppercase | `HELLO WORLD` |
| `capitalize()` | First character uppercase, all others lowercase | `Hello world` |
| `title()` | First letter of each word uppercase, others lowercase | `Hello World` |
| `swapcase()` | Uppercase becomes lowercase and the reverse | `HELLO World` |
You can check the table by running each method on the same string:
s = "hello wORLD"
print(s.lower()) # hello world
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
print(s.title()) # Hello World
print(s.swapcase()) # HELLO WworldThe swapcase() result above is HELLO Wworld? No. Run it and you will see HELLO World turn into HELLO wORLD only for mixed input. For "hello wORLD", swapcase() prints HELLO World.
Characters that have no case, such as digits, spaces, and punctuation, pass through unchanged.
Common mistake: not keeping the result
Because strings are immutable, calling a case method on its own line does nothing useful.
name = "ada"
name.upper() # result is thrown away
print(name) # ada
name = name.upper() # assign to keep it
print(name) # ADAcapitalize() lowercases the rest
capitalize() does more than uppercase the first letter. It also lowercases every other character. This damages names and acronyms.
print("mcDonald".capitalize()) # Mcdonald
print("NASA report".capitalize()) # Nasa reportIf you only want to change the first letter, slice the string instead:
text = "mcDonald"
print(text[:1].upper() + text[1:]) # McDonaldThis version assumes text is not empty. With an empty string it returns an empty string, since slices do not raise errors.
title() and apostrophes
title() treats any non-letter as a word boundary. An apostrophe therefore starts a new "word".
print("they're here".title()) # They'Re HereThe standard library function string.capwords splits on whitespace only, so it handles this case better. It also collapses runs of whitespace into single spaces.
import string
print(string.capwords("they're here")) # They're HereEven capwords will not handle names like McDonald or small words like "of" in titles. For those, you need your own rules.
Case changes can alter length
Case conversion follows Unicode rules, and in some languages one character maps to several. The German letter ß is a common example.
word = "straße"
print(word.upper()) # STRASSE
print(len(word)) # 6
print(len(word.upper())) # 7Two things follow from this. First, you cannot assume s.upper() has the same length as s, so do not reuse indexes from the original. Second, upper() followed by lower() does not always return the original text: "straße".upper().lower() gives strasse.
Testing case
Three related methods answer yes/no questions: isupper(), islower(), and istitle(). They return False for a string with no cased letters.
print("ABC".isupper()) # True
print("ABC1".isupper()) # True
print("123".isupper()) # False
print("Hello World".istitle()) # TrueComparing text
Using lower() to compare strings works for plain English text, but it can miss matches in other languages. The next chapter covers casefold(), which is designed for that job.
Exercise
What does this code print, and why? label = "wOrLd" label.upper() print(label.capitalize())
Show answer
It prints World. The label.upper() call returns a new string that is discarded, so label is unchanged. capitalize() then uppercases the first character and lowercases all the others, giving World.