Sub topic 6
Changing case
This chapter covers the five str methods that change letter case: lower, upper, capitalize, title, and swapcase. It assumes you know basic Python syntax, str literals and indexing, and how to read simple if statements and for loops. Earlier chapters covered the fact that strings are immutable. Every method here returns a new string and leaves the original unchanged.
The five case methods
Each method takes no arguments and returns a new string.
| Method | What it does | Example input | Result |
|---|---|---|---|
| `lower()` | Converts every cased character to lowercase | `"Hello, World"` | `"hello, world"` |
| `upper()` | Converts every cased character to uppercase | `"Hello, World"` | `"HELLO, WORLD"` |
| `capitalize()` | Uppercases the first character and lowercases the rest | `"hELLO, wORLD"` | `"Hello, world"` |
| `title()` | Uppercases the first letter of each word and lowercases the rest | `"hello, world"` | `"Hello, World"` |
| `swapcase()` | Swaps uppercase to lowercase and lowercase to uppercase | `"Hello"` | `"hELLO"` |
A "cased" character is a letter that has uppercase and lowercase forms. Digits, spaces, and punctuation have no case, so these methods pass them through unchanged.
s = "Hello, World 42"
print(s.lower()) # hello, world 42
print(s.upper()) # HELLO, WORLD 42
print(s.swapcase()) # hELLO, wORLD 42
print(s.capitalize()) # Hello, world 42
print(s.title()) # Hello, World 42
print(s) # Hello, World 42 (unchanged)Assign the result
Because strings are immutable, calling a case method and discarding the result does nothing useful. This is a common bug.
s = "abc"
s.upper() # result thrown away
print(s) # abc
s = s.upper() # rebind the name to the new string
print(s) # ABCPython does not warn you about the first form, because it is valid code. If a case change seems to have no effect, check that you assigned the return value.
capitalize does more than uppercase the first letter
capitalize() also lowercases everything after the first character. This surprises people who expect it to leave the rest alone.
print("python".capitalize()) # Python
print("PYTHON".capitalize()) # Python
print("iPhone".capitalize()) # Iphone
print("".capitalize() == "") # TrueIf you only want to change the first character and keep the rest as it is, use slicing:
def upper_first(text):
return text[:1].upper() + text[1:]
print(upper_first("iPhone")) # IPhone
print(upper_first("")) # (empty string, no error)The slice text[:1] is safe on an empty string, while text[0] would raise IndexError.
title and its apostrophe problem
title() decides where words start by looking for letters that follow a non-letter. It does not know about English grammar or contractions, so an apostrophe starts a new "word".
print("they're here".title()) # They'Re Here
print("o'neil".title()) # O'Neil
print("rock-n-roll".title()) # Rock-N-Roll
print("3rd place".title()) # 3Rd PlaceThe first line shows the problem: They'Re is wrong. The second line looks right only by luck. Digits also count as a non-letter boundary, so 3rd becomes 3Rd.
The standard library offers string.capwords, which splits on whitespace, capitalizes each piece, and rejoins with single spaces:
import string
print(string.capwords("they're here")) # They're Here
print(string.capwords("hello-world")) # Hello-worldNotice that capwords also collapses runs of whitespace into one space, and it only treats whitespace as a word boundary. Neither function is a full solution for names or titles. Names such as McDonald or van der Berg need rules that no simple method supplies.
Non-ASCII text and length changes
The case methods follow Unicode rules, so they work on accented letters and many other scripts.
print("élan".upper()) # ÉLAN
print("ÀÉÎ".lower()) # àéî
print("привет".upper()) # ПРИВЕТSome conversions change the length of the string, because a single character can map to several. The German sharp s is the standard example:
word = "straße"
print(len(word)) # 6
print(word.upper()) # STRASSE
print(len(word.upper())) # 7This has two consequences. First, you cannot assume that s.upper() has the same length as s, so any stored index positions from the original may not line up with the result. Second, case conversion is not always reversible:
print("straße".upper().lower()) # strasseThe round trip gives strasse, not straße. Do not use upper().lower() to "normalize" text and expect to recover the original.
Checking case without converting
Each conversion method has a matching test method that returns a bool: islower, isupper, and istitle.
print("abc".islower()) # True
print("ABC".isupper()) # True
print("Hello World".istitle()) # True
print("abc1".islower()) # True (digits are ignored)
print("123".islower()) # False (no cased characters)These methods need at least one cased character to return True. A string of only digits is neither lower nor upper. Use them when you want to inspect a string, for example to reject an all-uppercase username, without building a new string.
Case methods and comparison
A common first attempt at case-insensitive comparison is to lowercase both sides:
a = "Hello"
b = "HELLO"
print(a.lower() == b.lower()) # TrueFor plain English text this works. For text with characters like ß, lower() is not enough, because it leaves ß unchanged while "SS".lower() gives ss. The next chapter covers casefold, which is designed for caseless matching. Use lower and upper when you want to display text in a particular case, and use casefold when you want to compare it.
Choosing a method
Putting it together
This function formats a list of raw heading strings. It removes extra whitespace, applies a consistent case, and avoids the apostrophe problem by using capwords.
import string
def format_heading(raw):
return string.capwords(raw.strip())
headings = [" the QUICK brown fox ", "they're HERE", "PYTHON basics"]
for h in headings:
print(format_heading(h))
# The Quick Brown Fox
# They're Here
# Python BasicsHere capwords lowercases the rest of each word, which is why QUICK becomes Quick.
Common mistakes
- Calling
s.upper()without assigning the result. The original string stays the same. - Expecting
capitalize()to keep the rest of the word as is. It lowercases it. - Using
title()on text with apostrophes or digits and gettingThey'Reor3Rd. - Assuming
upper()preserves length."straße".upper()is one character longer. - Using
lower()to compare text that may contain non-English characters. Prefercasefold(). - Treating
islower()as "has no uppercase letters". It also returnsFalsewhen there are no letters at all.
Exercises
Exercise
What does this code print, and why? s = "hELLO wORLD" s.title() print(s.capitalize())
Show answer
It prints "Hello world". The call to s.title() builds a new string that is immediately discarded, because its result is not assigned. The capitalize() call uppercases the first character and lowercases all the rest, so the second word stays lowercase.
Exercise
Write a function upperfirst(text) that uppercases only the first character and leaves the rest unchanged. It must not raise an error on an empty string. What does upperfirst("eBay") return?
Show answer
def upperfirst(text): return text[:1].upper() + text[1:] upperfirst("eBay") returns "EBay". Slicing with text[:1] returns an empty string when text is empty, so no IndexError occurs. Using capitalize() would give "Ebay" instead, because it lowercases the rest.
Exercise
"they're here".title() gives "They'Re Here". Name one standard-library function that fixes this, and explain why the Unicode example "straße".upper() makes it unsafe to assume that upper() keeps the length of a string.
Show answer
string.capwords("they're here") returns "They're Here", because it splits only on whitespace. For the second part, "straße" has 6 characters but "straße".upper() is "STRASSE", with 7, because the single character ß maps to two letters. Indexes saved from the original string may not match the uppercase result.