Reference · module 5
Strings up close
Everything this module explains, on one page.
Slicing
Cut a piece out of a string.
- A slice takes a range: word[1:4] gives characters 1, 2 and 3. The start is included, the stop is not.
- Leave an end out and Python fills it in: word[:3] is the first three, word[3:] is everything from 3 onward.
- Negative counts from the end: word[-1] is the last character, word[:-1] is everything but the last.
The mistake you are about to make
word[len(word)]
word[-1]
A length of five suggests the last character is number five. Counting starts at zero, so this is an IndexError. The last one is word[-1], no length needed.
String methods
Clean and reshape text.
- A string method never changes the string. It returns a new one, and the old one is untouched.
- strip() removes whitespace at both ends. lower() and upper() change case. All three hand back a copy.
- replace(old, new) swaps every occurrence. Nothing found means nothing changed, and no error.
The mistake you are about to make
text.strip()
text = text.strip()
It looks like append — do this to the thing. Strings never change: strip() returns a new one and the old one stays exactly as it was.
f-strings
Put values inside text.
- Put f before the quote and any name in braces is replaced: f"Hi {name}". Without the f, the braces stay as text.
- Anything that has a value fits in the braces, not just a name: f"{a + b}" or f"{len(items)}".
- A colon adds formatting: f"{price:.2f}" shows two decimals. This rounds the display, not the value.
The mistake you are about to make
"Hi {name}"
f"Hi {name}"
The braces look like signal enough. Without the f in front of the quote they are just characters, and Hi {name} is what appears on screen.
split and join
Move between a string and a list.
- split() cuts a string into a list. With no argument it splits on any whitespace and drops the empties.
- Give it a separator to be exact: "a,b".split(",") gives ["a", "b"].
- join goes the other way, and the separator is the string you call it on: ", ".join(names).
The mistake you are about to make
names.join(", ")
", ".join(names)
Join reads as "join this list", so it gets called on the list. It is the other way round: the method belongs to the separator, and the list is the argument.
Searching in text
Ask what a string contains.
- in answers yes or no: "an" in "banana" is True. It is the simplest check and usually the right one.
- startswith and endswith check an edge, which is what you want for prefixes and file extensions.
- find gives the position, or -1 when there is none. It never raises, so -1 has to be checked for.
The mistake you are about to make
if word.find("a"):
if "a" in word:
Find returns a position, and a match at the start gives zero, which is falsy. The question "is it there" is what in answers; find needs an explicit -1 check.