StringsChapter 17 of 114
Modify Strings
Change case, trim whitespace and replace text - always by making a new string.
Every change makes a new string
Say it once more, because it explains every method on this page: strings are immutable. A "modifying" method returns a new string and leaves the original where it was.
name = " Ada Lovelace "
print(repr(name.strip()))
print(repr(name))Output
'Ada Lovelace' ' Ada Lovelace '
repr() shows the quotes and escapes, which is how you can see the spaces at all.
Case
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
print(name.title())
print("hELLO".capitalize())Output
ADA LOVELACE ada lovelace Ada Lovelace Hello
capitalize() uppercases the first character and lowercases everything else, which is not the same as title().
Trimming whitespace
padded = "\t hello \n"
print(repr(padded.strip()))
print(repr(padded.lstrip()))
print(repr(padded.rstrip()))Output
'hello' 'hello \n' '\t hello'
With an argument, strip() removes any of those characters from the ends — it is a set of characters, not a prefix:
print("xxhelloxx".strip("x"))
print("www.example.com".strip("wmoc."))Output
hello example
print("www.example.com".removeprefix("www."))
print("report.pdf".removesuffix(".pdf"))Output
example.com report
Replacing
line = "one,two,three"
print(line.replace(",", " | "))
print("aaa".replace("a", "b", 2))Output
one | two | three bba
The third argument caps how many replacements happen.
Splitting and joining
split() breaks a string into a list; join() puts one back together:
line = "one,two,three"
parts = line.split(",")
print(parts)
print(" and ".join(parts))Output
['one', 'two', 'three'] one and two and three
The separator goes between items, so three items produce two separators. Note which side it is written on: the separator is the string, and the list is the argument. ",".join(parts) reads backwards the first few times and then never again.
With no argument, split() breaks on any run of whitespace and drops the empty pieces, which is almost always what you want for typed input:
print(" a b \n c ".split())
print(" a b \n c ".split(" "))Output
['a', 'b', 'c'] ['', '', 'a', '', '', 'b', '\n', 'c', '']
Building a string in a loop
Adding to a string in a loop makes a new string every time. For a few items nobody notices; for many, collect them and join once:
words = ["fast", "and", "readable"]
sentence = " ".join(words)
print(sentence)Output
fast and readable
Test yourself
2 questionsWhat does "www.example.com".strip("wmoc.") give?
Show the answer
"example" — strip takes a set of characters and chews any of them off both ends. Use removeprefix for an exact prefix.
What is the difference between split() and split(" ")?
Show the answer
split() breaks on any run of whitespace and drops empty pieces — That is why bare split() is the right one for text a person typed.
Concatenation
Joining strings with +, repeating with *, and why numbers need converting first.