Sub topic 13
Common string methods
This chapter assumes you can run Python code and that you know how to index and slice a string. You should also know that strings are immutable, which the previous chapters cover. Here you will learn the methods you reach for daily, the mistakes people make with them, and how to choose between similar ones.
Methods return new strings
A method is a function attached to an object, called with dot syntax. Because a str cannot change after it is created, every string method returns a new object and leaves the original alone. Methods that split a string return a list instead.
The most common error follows from this: calling a method and discarding the result.
s = "python"
s.upper()
print(s)
s = s.upper()
print(s)The first print shows python and the second shows PYTHON. The first call built a new string and nothing kept it. Rebinding the name s is how you "change" a string.
Since each method returns a string, you can chain calls. Each step works on the result of the previous one.
raw = " Hello, World "
print(raw.strip().lower().split(","))
print(", ".join(["a", "b", "c"]))
print("banana".replace("a", "o"))
print("banana".count("an"))This prints ['hello', ' world'], then a, b, c, then bonono, then 2. Notice the leading space in ' world'. Splitting on "," does not remove whitespace around the pieces.
Trimming whitespace and affixes
strip() removes whitespace from both ends. lstrip() and rstrip() handle one side each. Whitespace includes spaces, tabs, and newlines, so strip() is the usual way to clean a line read from a file or from user input.
If you pass an argument, it is treated as a set of characters to remove, not as a substring. This surprises many people.
print("xxhixx".strip("x"))
print("moon.com".strip("com."))
print("report.txt".removesuffix(".txt"))
print("v2.1".removeprefix("v"))This prints hi, n, report, and 2.1. The second line removes every leading and trailing character that is any of c, o, m, or ., so only n is left. To remove an exact prefix or suffix, use removeprefix() and removesuffix(). They were added in Python 3.9.
Searching
Use in when you only need a yes or no answer. Use startswith() and endswith() for the ends of a string. Both accept a tuple of alternatives. Use find() or index() when you need the position.
s = "error: disk full"
print("disk" in s)
print(s.startswith("error"))
print(s.endswith(("full", "empty")))
print(s.find("disk"))
print(s.find("tape"))
try:
s.index("tape")
except ValueError as e:
print("ValueError:", e)The output is True, True, True, 7, -1, and then ValueError: substring not found.
find() returns -1 when the text is missing, while index() raises ValueError. A common bug is writing if s.find("x"):. A match at position 0 is falsy, and the missing-case value -1 is truthy, so the test gives the wrong answer in both cases. Compare with -1 explicitly, or use in.
count() counts non-overlapping occurrences. "aaaa".count("aa") is 2, not 3.
Replacing
replace(old, new) replaces every occurrence. A third argument limits how many replacements are made, counted from the left. Replacement is case-sensitive and literal. It does not understand patterns, so use the re module for those.
print("a-b-c-d".replace("-", "+", 2))This prints a+b+c-d.
Splitting and joining
split() and join() are opposites, and they behave in ways that are worth learning exactly.
line = "name=Ada=Lovelace"
print(line.split("=", 1))
print(line.partition("="))
print("a,b,c".rsplit(",", 1))
print("a b c".split())
print("a b".split(" "))
print("one\ntwo\n".splitlines())The output is:
['name', 'Ada=Lovelace']
('name', '=', 'Ada=Lovelace')
['a,b', 'c']
['a', 'b', 'c']
['a', '', 'b']
['one', 'two']split(sep, maxsplit)stops aftermaxsplitsplits. A limit of 1 is how you split on only the first separator.rsplit()does the same from the right.partition(sep)always returns a 3-tuple of before, separator, and after. If the separator is missing, you get the whole string and two empty strings. This makes it safe to unpack.split()with no argument splits on any run of whitespace and discards empty pieces.split(" ")with one space splits on every single space and keeps empty strings.splitlines()handles\n,\r\n, and other line endings, and it does not add a trailing empty item.
join() is called on the separator, and it takes any iterable of strings. Every item must already be a str.
nums = [1, 2, 3]
try:
",".join(nums)
except TypeError as e:
print("TypeError:", e)
print(",".join(str(n) for n in nums))The first call fails with TypeError: sequence item 0: expected str instance, int found. The second prints 1,2,3.
Prefer join() to building a long string with += in a loop. Each += may copy the whole string, and join() builds the result once.
Case methods
| Method | Example | Result |
|---|---|---|
| `lower()` | `"Ada".lower()` | `ada` |
| `upper()` | `"Ada".upper()` | `ADA` |
| `capitalize()` | `"hello WORLD".capitalize()` | `Hello world` |
| `title()` | `"hello world".title()` | `Hello World` |
| `swapcase()` | `"Ada".swapcase()` | `aDA` |
| `casefold()` | `"Straße".casefold()` | `strasse` |
For case-insensitive comparison, use casefold() instead of lower(). It is more aggressive and handles cases such as the German ß.
a = "Straße"
b = "STRASSE"
print(a.lower() == b.lower())
print(a.casefold() == b.casefold())This prints False and then True. Be careful with title(). It capitalizes after any non-letter, so "it's".title() gives It'S.
Testing what a string contains
The is...() methods return True or False. Each one also returns False for an empty string.
print("123".isdigit(), "12.5".isdigit())
print("abc".isalpha(), "abc1".isalnum())
print(" ".isspace(), "".isalpha())This prints True False, then True True, then True False.
isdigit() is False for "12.5" and for "-3", because the . and - are not digits. These methods are not a safe way to validate numbers. To check whether text is a number, attempt the conversion and catch ValueError, as the later chapter on converting strings and numbers shows.
Padding and alignment
zfill(width) pads a numeric string with leading zeros. ljust(), rjust(), and center() pad with spaces or a fill character you choose. For most output you will use f-string format specifiers instead, which come next.
print("7".zfill(3))
print("ab".center(6, "*"))
print("ab".ljust(5, ".") + "|")This prints 007, **ab**, and ab...|.
Common errors
- Discarding the return value, as in
s.strip()on its own line. - Treating
strip("abc")as removing a substring instead of a character set. - Testing
find()for truthiness. - Calling
join()on a list that contains non-strings. - Using
split(" ")on text that may contain repeated spaces or tabs. - Using
lower()instead ofcasefold()for case-insensitive comparison of international text.
Exercise
A log line is " ERROR:disk:/dev/sda1:full ". Using only methods from this chapter, write one expression that produces the list ['error', 'disk', '/dev/sda1', 'full']. Then say what " a b ".split(" ") returns and why it differs from " a b ".split().
Show answer
" ERROR:disk:/dev/sda1:full ".strip().lower().split(":") returns ['error', 'disk', '/dev/sda1', 'full']. strip() removes the outer spaces, lower() lowercases the text, and split(":") cuts at each colon. " a b ".split(" ") returns ['', '', 'a', '', 'b', ''] because splitting on a single space keeps an empty string for each extra space. " a b ".split() returns ['a', 'b'] because with no argument it splits on runs of whitespace and drops empty pieces.
Exercise
What does this code print, and which line has a bug that makes the filtering wrong? path = "archive.tar.gz" print(path.rsplit(".", 1)) print(path.removesuffix(".gz")) print(path.strip(".gz"))
Show answer
It prints ['archive.tar', 'gz'], then archive.tar, then archive.tar. Wait for the third line: strip(".gz") removes any leading or trailing characters from the set {".", "g", "z"}. The leading a is not in the set, so nothing is removed at the start. At the end, z, g, and . are removed, then r stops it, so the result is archive.tar. This happens to match the second line here, but it is the wrong tool. For a name like "gz-notes.gz", strip(".gz") would also eat the leading "gz". The buggy approach is the third line, since strip() takes a set of characters. removesuffix(".gz") removes exactly that suffix.