Strings and f-strings

Python · Essentials · 10 min

Almost every program reads, builds or prints text, and f-strings are the modern way to format it.

A str is an immutable sequence of Unicode characters. Single and double quotes are equivalent; triple quotes ('''...''') span lines. A backslash starts an escape like \n or \t; prefix with r for a raw string where backslashes are literal, which is handy for regexes and Windows paths.

Strings support sequence operations: len(s), indexing s[0], s[-1] for the last character, in for substring tests, + to concatenate and * to repeat. Because they are immutable, every method returns a new string:

  • s.upper(), s.lower(), s.strip() (remove surrounding whitespace)
  • s.split(",") returns a list; ", ".join(items) is the reverse
  • s.replace(old, new), s.startswith(prefix), s.find(sub) (-1 if missing)

An f-string (f"...") evaluates expressions inside braces and inserts the result. After a colon you can add a format spec:

  • {price:.2f} two decimal places, {n:,} thousands separators, {ratio:.1%} percent
  • {name:>10} right-align in 10 characters, {name:<10} left, {name:^10} centre
  • {x!r} uses repr(); {x=} prints x= followed by the value, great for debugging

Since Python 3.12 you can even reuse the same quote type inside the braces. Build big strings by collecting parts in a list and calling "".join(parts), not by += in a loop.

Example

name = "Ada Lovelace"
print(name.upper(), len(name))        # ADA LOVELACE 12
print(name.split())                   # ['Ada', 'Lovelace']
print("-".join(["2026", "10", "16"])) # 2026-10-16
print("love" in name.lower())         # True

price, qty = 4.5, 1234
print(f"{qty:,} items at ${price:.2f}")   # 1,234 items at $4.50
print(f"[{'left':<6}][{'right':>6}]")     # [left  ][ right]
print(f"{0.256:.1%}")                     # 25.6%

total = price * 3
print(f"{total=}")                    # total=13.5
print(r"C:\new\table")                # C:\new\table

Remember

  • Strings are immutable; methods return new strings
  • Use f-strings with format specs like :.2f, :,, :>10
  • sep.join(list) and s.split(sep) convert between strings and lists

Watch out for

  • Calling s.upper() and expecting s itself to change.
  • Concatenating in a loop instead of collecting parts and joining once.

Check yourself

  1. What does `f"{7/3:.2f}"` produce?
  2. After `s = "hi"; s.upper()`, what is `s`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/stdtypes.html#text-sequence-type-str