Python String Methods: Chaining strip(), lower() and More
Chaining string methods means calling one method on the result of another, as in text.strip().lower(), so several steps fit on one line.
Read String Methods first. This lesson also uses Lists.
Call a method on a result
Python runs a chain from left to right. Each method works on the value the
previous one gave back. This lesson also uses .strip(), which gives back the
text without spaces at its start and end.
text = " Red RED red "
print(text.strip().lower())
.strip() removes the outer spaces, then .lower() lowercases that result.
It prints red red red.
Chain the same method twice
.replace() gives back a string, so you can call .replace() on it again.
word = "banana"
print(word.replace("a", "A").replace("n", "N"))
This prints bANANA one swap at a time: first every a, then every n.
The b stays lowercase because neither replacement matches it.
Order can change the answer
Each step sees only the text the step before it produced.
text = "Cat cat"
print(text.lower().replace("cat", "dog"))
print(text.replace("cat", "dog").lower())
The first line prints dog dog: lowercasing first lets both words match. The
second prints cat dog, because "Cat" did not match when .replace() ran.
Put the step that makes text uniform (.strip(), .lower()) first.
Where a chain stops
A chain only works while each result has the next method. .split() gives
back a list, and lists have no .lower().
text = "Red Green"
words = text.lower().split()
print(words)
This prints ['red', 'green']. The other order fails:
text.split().lower() # raises AttributeError: 'list' object has no attribute 'lower'
Lowercase before you split. After .split() you have a list, so use list tools
instead.
Note: Long chains are hard to read and hard to debug, because you can't see the middle values. When a chain goes wrong, break it into separate lines and print each step. This lesson uses fixed strings; real text, such as file lines or typed answers, can also contain tabs, newlines or unexpected characters.
See also: Cleaning input() answers, Reading Text Files.
Your turn
entry is a messy line from a guest list. Use one chain to strip it,
lowercase it, replace "-" with " " and split it into words. Print the list,
then how many words it holds.
entry = " Mia-Rose-SMITH "
# add your code: one chain of strip, lower, replace and split, then print the list and its length
Expected output
['mia', 'rose', 'smith']
3