Sub topic 13
Common string methods
This chapter assumes you can index and slice strings and know that strings are immutable. A string method is a function attached to a string, called with a dot, such as text.upper().
Methods return new strings
Because strings cannot change, no method edits the original. Each method returns a new object. If you do not store the result, it is lost.
title = "python"
title.upper()
print(title)
title = title.upper()
print(title)The first print shows python, because the uppercase result was discarded. The second shows PYTHON, because the name was rebound to the new string.
Cleaning and splitting
strip() removes whitespace from both ends. lower() and upper() change case. split(sep) returns a list of pieces, and join() does the reverse. Since each method returns a string or a list, calls can be chained.
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. Note the leading space in ' world'. Splitting on "," keeps the space that followed the comma.
join() is called on the separator, not on the list. The list must contain only strings, or you get a TypeError.
Searching and testing
Several methods answer questions about the content.
| Method | Returns | Example result |
|---|---|---|
| `startswith(prefix)` | `bool` | `"report.csv".startswith("rep")` is `True` |
| `endswith(suffix)` | `bool` | `"report.csv".endswith(".txt")` is `False` |
| `find(sub)` | index, or `-1` if absent | `"banana".find("nan")` is `2` |
| `index(sub)` | index, or raises `ValueError` | `"banana".index("x")` raises |
| `isdigit()` | `bool` | `"123".isdigit()` is `True` |
Use in for a plain membership test, as in "nan" in "banana". Reach for find() only when you need the position.
Splitting without an argument
Calling split() with no argument splits on any run of whitespace and ignores leading and trailing whitespace. This is usually what you want for words.
line = " one two\tthree\n"
print(line.split())
print(line.split(" "))The first call prints ['one', 'two', 'three']. The second splits on every single space, so it produces empty strings between the extra spaces.
Choosing a method
Common errors
- Calling a method and ignoring the result, as in the first example.
- Using
find()result as a truthy value. It returns0for a match at the start and-1(truthy) for no match. - Passing non-strings to
join(). Convert first, for example",".join(str(n) for n in numbers).
Exercise
What does " a-b-c ".strip().split("-") return, and does the original string change?
Show answer
It returns ['a', 'b', 'c']. The original string is unchanged, because strip() and split() return new objects and strings are immutable.
Exercise
Why is if text.find("x"): a poor way to test whether "x" appears in text?
Show answer
find() returns -1 when the text is absent, which is truthy, and 0 when "x" is at the start, which is falsy. Use if "x" in text: or compare the result to -1.