Strings and f-strings

RequiredRequired

Juan Camilo ZúñigaBackend & data developer

Strings (str) are immutable sequences of Unicode characters. Single and double quotes are equivalent; triple quotes span several lines.

f-strings

Since Python 3.6, an f before the quotes lets you put expressions inside {}:

name, total = "Ada", 1234.5
f"{name} owes {total:,.2f}"     # 'Ada owes 1,234.50'
f"{total=}"                      # 'total=1234.5' (3.8+): handy for debugging

After the : comes a format spec: .2f for two decimals, , for thousands, >10 to right-align in ten characters. Since 3.12, f-strings can also reuse the same quote type inside the braces.

Everyday methods

"  hello ".strip()               # 'hello'
"a,b,c".split(",")               # ['a', 'b', 'c']
"-".join(["2026", "11", "22"])   # '2026-11-22'
"Python".lower().startswith("py")
"report.csv".removesuffix(".csv")  # 'report' (3.9+)

Methods return a new string; the original never changes. Building a long string in a loop with += is slow; collect the pieces in a list and "".join(pieces) at the end.

Indexing and slicing

s[0] is the first character and s[-1] the last. s[1:4] takes positions 1 to 3, and s[::-1] reverses it.