StringsChapter 22 of 114
String Methods
The methods you will actually reach for, grouped by what you want done.
Asking questions
These return True or False and are the backbone of input checking:
name = "report.pdf"
print(name.startswith("rep"))
print(name.endswith(".pdf"))
print("abc123".isalnum())
print("123".isdigit())
print("abc".isalpha())
print(" ".isspace())Output
True True True True True True
startswith and endswith accept a tuple, which beats a chain of or:
for name in ["a.png", "b.txt", "c.jpg"]:
print(name, name.endswith((".png", ".jpg")))Output
a.png True b.txt False c.jpg True
print("-4".isdigit())
print("3.5".isdigit())Output
False False
Finding
find() gives the index, or -1 when there is nothing there. index() does the same but raises instead, and count() tallies:
line = "one,two,one"
print(line.find("two"))
print(line.find("three"))
print(line.count("one"))Output
4 -1 2
Use in when you only want to know whether it is there, and find when you need to know where.
Changing case
print("ada".upper())
print("ADA".lower())
print("ada lovelace".title())
print("Ada".swapcase())Output
ADA ada Ada Lovelace aDA
For case-insensitive comparison, casefold() is the thorough version of lower() and handles scripts where the two differ:
print("Straße".casefold() == "strasse".casefold())
print("Straße".lower() == "strasse".lower())Output
True False
Splitting
line = "a,b,c"
print(line.split(","))
print(line.rsplit(",", 1))
print("first line\nsecond".splitlines())
print("key=value=more".partition("="))Output
['a', 'b', 'c']
['a,b', 'c']
['first line', 'second']
('key', '=', 'value=more')partition() always gives exactly three pieces, which makes it safe to unpack without checking the length first.
Padding
print("7".zfill(3))
print("ab".ljust(6, ".") + "|")
print("ab".rjust(6, ".") + "|")
print("ab".center(6, ".") + "|")Output
007 ab....| ....ab| ..ab..|
A quick reference
| Method | Does |
|---|---|
strip() | remove whitespace from both ends |
removeprefix() | drop an exact prefix |
replace(a, b) | swap every a for b |
split(sep) | break into a list |
join(items) | glue a list together |
startswith(x) | test the beginning |
find(x) | index, or -1 |
zfill(n) | pad with leading zeros |
encode() | turn into bytes |
Every one of these returns something new. None of them change the string you called them on.
Test yourself
3 questionsWhat does "-4".isdigit() give?
Show the answer
False — The minus sign is not a digit. isdigit is not a number check; try converting and catch ValueError instead.
What does "one,two".find("three") give?
Show the answer
-1 — find returns -1 when there is no match. index() raises instead, and 'in' is best when you only need yes or no.
What does "key=value=more".partition("=") give?
Show the answer
('key', '=', 'value=more') — partition always gives exactly three pieces, so it is safe to unpack without checking the length.
Text and Unicode
What a character really is, and the difference between text and bytes.