← All lessons
Python intermediate · Lesson 4 of 11

Strings in depth

Much of programming is turning messy text into data and data back into tidy text. These are the string methods you'll use most.

split() breaks a string into a list. With no argument it splits on any run of spaces; give it a separator to split on that instead. join() does the opposite: it's called on the separator and glues a list of strings together.

line = "Ana,31,Lima"
parts = line.split(",")
print(parts)
print(" | ".join(parts))
print("one  two three".split())
Prints
['Ana', '31', 'Lima']
Ana | 31 | Lima
['one', 'two', 'three']

strip() removes spaces (and line breaks) from both ends, which text typed by people or read from files nearly always needs. lstrip() and rstrip() do one side.

raw = "   hello  "
print("[" + raw.strip() + "]")
Prints
[hello]

To search: in asks whether a piece of text appears, find() gives the index where it starts (or -1 if it's not there), count() counts it, and startswith() and endswith() check the ends. Methods like isdigit() ask what a string is made of.

email = "[email protected]"
print("@" in email)
print(email.find("@"))
print(email.endswith(".example"))
print("2026".isdigit(), "20a6".isdigit())
Prints
True
3
True
True False

Methods can be chained, because each gives back a string the next can work on: text.strip().lower().

f-strings can format what they fill in. After the value, a colon and a format spec say how to show it: :.2f is 2 decimal places, :, adds thousands commas, :% shows a percentage, and :>8 pads to 8 characters, lined up on the right (< left, ^ centre). They can be combined.

price = 1234.5
rate = 0.075
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{rate:.1%}")
print(f"[{'hi':>5}]")
Prints
1234.50
1,234.50
7.5%
[   hi]

Strings can also span several lines with triple quotes ("""..."""), and special characters are written with a backslash: \n is a new line and \t a tab.

Practice

What does this print?

print("a-b-c".split("-"))
More info

Quick reference

s.split(sep) / sep.join(list)String to list / list to string.
s.strip()Remove spaces and line breaks from both ends.
in, find, countIs it there? Where? How many times?
startswith endswith isdigitCheck the start, the end, or whether it's all digits.
f"{x:.2f}" f"{x:,}" f"{x:.0%}"2 decimals, thousands commas, a percentage.
f"{s:>8}"Pad to 8 characters, right-aligned (< left, ^ centre).

Related courses