Strings and f-string formatting
Text in Python: literals and escapes, slicing, the str methods you use every day, f-strings with the complete format-spec mini-language, and the step from str to bytes (encodings, Unicode normalization). Every runnable block is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| put a value in text | f-string | f"{name} has {n} items" |
| show 2 decimals | :.2f |
f"{3.14159:.2f}" → 3.14 |
| add thousands separators | :, or :_ |
f"{1234567:,}" → 1,234,567 |
| show a percentage | :.1% |
f"{0.256:.1%}" → 25.6% |
| pad a number with zeros | :05d or str.zfill |
f"{42:05d}" → 00042 |
| align in a column | :<10, :>10, :^10 |
f"{'id':>6}" → ' id' |
| choose the width at run time | nested braces | f"{x:>{width}.{prec}f}" |
| debug-print a name and its value | = |
f"{total=}" → total=42 |
| show quotes and escapes | !r or repr() |
f"{s!r}" → 'a\tb' |
| format a date | strftime codes in the spec | f"{d:%Y-%m-%d}" |
| show hex or binary | :x, :#x, :08b |
f"{255:#x}" → 0xff |
| use scientific notation | :.2e |
f"{12345:.2e}" → 1.23e+04 |
| print a literal brace | double it | f"{{x}}" → {x} |
| remove whitespace at both ends | s.strip() |
" a ".strip() → 'a' |
| remove a known prefix or suffix | removeprefix, removesuffix |
"v1.2".removeprefix("v") |
| split on whitespace | s.split() |
"a b\tc".split() → ['a', 'b', 'c'] |
| split on a delimiter, once | s.split(sep, 1) or partition |
"k=v=w".split("=", 1) |
| split into lines | s.splitlines() |
handles \n and \r\n |
| join a list into text | sep.join(items) |
", ".join(["a", "b"]) |
| join numbers | sep.join(map(str, nums)) |
"-".join(map(str, [1, 2])) |
| test the start or end | startswith / endswith (a tuple works) |
f.endswith((".csv", ".tsv")) |
| find a substring | in, find (−1), index (raises) |
"py" in "python" |
| count occurrences | s.count(sub) |
"banana".count("a") → 3 |
| replace text | s.replace(old, new, count) |
"a-b-c".replace("-", "", 1) |
| replace or delete many characters | str.maketrans + translate |
see Replace and translate |
| compare without case | a.casefold() == b.casefold() |
handles ß and other letters |
| reverse a string | s[::-1] |
"abc"[::-1] → 'cba' |
| check that text is a whole number | s.isdecimal() |
"42".isdecimal() → True |
| repeat text | * |
"-" * 20 |
| build text in a loop | append to a list, then "".join(parts) |
faster than += in a loop |
| turn text into bytes | s.encode("utf-8") |
"é".encode() → b'\xc3\xa9' |
| turn bytes into text | b.decode("utf-8") |
errors="replace" to keep going |
| read an old file | open(path, encoding="latin-1") |
see Encodings |
| compare accented text reliably | unicodedata.normalize("NFC", s) |
"é" vs "e\u0301" |
| wrap long text | textwrap.fill(s, width=60) |
also textwrap.shorten, dedent |
Literals and escapes
Section titled “Literals and escapes”| Form | Example | Note |
|---|---|---|
| single or double quotes | 'it', "it's" |
same type; pick the one that avoids escapes |
| triple quotes | """line 1\nline 2""" |
keeps line breaks; docstrings |
| raw string | r"C:\new\data", r"\d+" |
backslashes stay literal; for regex and Windows paths |
| f-string | f"{x}", rf"\d{{{n}}}" |
combine with r |
| implicit concatenation | ("part one " "part two") |
adjacent literals join at compile time |
| bytes | b"abc", rb"\x00" |
not str |
| Escape | Meaning | Escape | Meaning |
|---|---|---|---|
\n |
line feed | \t |
tab |
\r |
carriage return | \\ |
one backslash |
\', \" |
quote | \0 |
null character |
\x41 |
char by 2 hex digits (A) |
\u00e9 |
char by 4 hex digits (é) |
\U0001F600 |
char by 8 hex digits | \N{SNOWMAN} |
char by Unicode name |
Indexing and slicing
Section titled “Indexing and slicing”| Expression | s = "Python" |
Note |
|---|---|---|
s[0], s[-1] |
'P', 'n' |
negative counts from the end |
s[1:4] |
'yth' |
start included, stop excluded |
s[:2], s[2:] |
'Py', 'thon' |
s[:i] + s[i:] == s |
s[-3:] |
'hon' |
last 3 |
s[::2] |
'Pto' |
every 2nd character |
s[::-1] |
'nohtyP' |
reversed |
s[10:] |
'' |
slices never raise |
s[10] |
IndexError |
indexes do |
len(s) |
6 |
code points, not bytes |
s = "Python"print(s[0], s[-1], s[1:4], s[:2], s[2:], s[-3:], s[::2], s[::-1])print(repr(s[10:]), repr(s[4:1]), s[:2] + s[2:] == s)code = "S01-2024-0042"store, year, number = code.split("-")print(store, int(year), int(number), code[-4:])P n yth Py thon hon Pto nohtyP'' '' TrueS01 2024 42 0042String methods
Section titled “String methods”Strings are immutable: every method returns a new string.
| Method | "hello WORLD" → |
Note |
|---|---|---|
lower() |
'hello world' |
|
upper() |
'HELLO WORLD' |
|
title() |
'Hello World' |
"o'brien".title() → "O'Brien" |
capitalize() |
'Hello world' |
the rest goes lower case |
swapcase() |
'HELLO world' |
|
casefold() |
'hello world' |
stronger lower() for comparisons: "ß" → "ss" |
Whitespace and padding
Section titled “Whitespace and padding”| Method | Example | Result |
|---|---|---|
strip(), lstrip(), rstrip() |
" a \n".strip() |
'a' |
strip(chars) |
"--a-b--".strip("-") |
'a-b' (a set of characters, not a prefix) |
removeprefix(p), removesuffix(s) |
"report.csv".removesuffix(".csv") |
'report' |
center(w, fill) |
"hi".center(6, "*") |
'**hi**' |
ljust(w), rjust(w) |
"7".rjust(3) |
' 7' |
zfill(w) |
"-42".zfill(5) |
'-0042' (keeps the sign) |
expandtabs(n) |
"a\tb".expandtabs(4) |
'a b' |
Search and test
Section titled “Search and test”| Method | Example | Result |
|---|---|---|
sub in s |
"ell" in "hello" |
True |
find(sub), rfind(sub) |
"hello".find("l"), "hello".find("z") |
2, -1 |
index(sub), rindex(sub) |
"hello".index("z") |
ValueError |
count(sub) |
"banana".count("an") |
2 (no overlaps) |
startswith(p), endswith(s) |
"a.csv".endswith((".csv", ".tsv")) |
True |
isdecimal() |
"042", "4.2", "-4" |
True, False, False |
isdigit(), isnumeric() |
"²".isdigit(), "½".isnumeric() |
True, True (wider than decimal) |
isalpha(), isalnum() |
"abc", "abc1" |
True, True |
isspace() |
" \t\n" |
True ("" is False) |
isupper(), islower(), istitle() |
"ABC1" |
True for isupper |
isascii() |
"café" |
False |
isidentifier() |
"total_2" |
True (valid variable name) |
Split and join
Section titled “Split and join”| Method | Example | Result |
|---|---|---|
split() |
" a b\tc\n".split() |
['a', 'b', 'c'] (runs of whitespace, ends dropped) |
split(sep) |
"a,b,,c".split(",") |
['a', 'b', '', 'c'] (empty fields kept) |
split(sep, maxsplit) |
"k=v=w".split("=", 1) |
['k', 'v=w'] |
rsplit(sep, maxsplit) |
"a.b.c".rsplit(".", 1) |
['a.b', 'c'] |
splitlines() |
"a\nb\r\n".splitlines() |
['a', 'b'] |
partition(sep) |
"key: val".partition(": ") |
('key', ': ', 'val') (always 3 parts) |
rpartition(sep) |
"a/b/c".rpartition("/") |
('a/b', '/', 'c') |
sep.join(iterable) |
"-".join(["a", "b"]) |
'a-b' (items must be str) |
line = " 2024-05-01, S01 , 458.94 , "fields = [f.strip() for f in line.split(",")]print(fields)print("a,b,,c".split(","), "k=v=w".split("=", 1), "a.b.c".rsplit(".", 1))print("Host: example.org:8080".partition(": "), "a\nb\r\nc".splitlines())print("-".join(["2024", "05", "01"]), ", ".join(map(str, [1, 2.5, None])))['2024-05-01', 'S01', '458.94', '']['a', 'b', '', 'c'] ['k', 'v=w'] ['a.b', 'c']('Host', ': ', 'example.org:8080') ['a', 'b', 'c']2024-05-01 1, 2.5, NoneReplace and translate
Section titled “Replace and translate”print("2024/05/01".replace("/", "-"), "a-b-c".replace("-", "", 1))table = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"})print("Grüße aus Köln".translate(table))drop_punct = str.maketrans("", "", ",.;!?") # third argument: delete theseprint("Hi, there! Ok?".translate(drop_punct))print(" ".join("too many spaces ".split())) # collapse whitespace2024-05-01 ab-cGruesse aus KoelnHi there Oktoo many spacesClean messy names
Section titled “Clean messy names”from pathlib import Path
for raw in Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()[:4]: clean = " ".join(raw.split()).title() print(f"{raw!r:28} -> {clean}")' josé GARCÍA ' -> José García"ZOË o'brien" -> Zoë O'Brien'françois dupont' -> François Dupont'Björk Guðmundsdóttir ' -> Björk Guðmundsdóttirf-strings
Section titled “f-strings”| Feature | Example | Result |
|---|---|---|
| any expression | f"{2 * 21}", f"{name.upper()}" |
'42' |
format spec after : |
f"{pi:.3f}" |
'3.142' |
conversion !r, !s, !a |
f"{s!r}" |
repr(s), str(s), ascii(s) |
| conversion and spec | f"{s!r:>12}" |
conversion first, then the spec |
self-documenting = |
f"{x=}", f"{x = }", f"{x=:.2f}" |
'x=3.14159'; spaces kept |
| nested spec | f"{x:{w}.{p}f}" |
width and precision from variables |
| literal braces | f"{{", f"}}" |
'{', '}' |
| same quotes inside (3.12+) | f"{d["key"]}" |
earlier versions need the other quote type |
| multi-line | f"""{a}\n{b}""" |
|
| date and time | f"{when:%Y-%m-%d %H:%M}" |
calls when.__format__ |
the format() built-in |
format(0.5, ".0%") |
'50%'; same spec language |
str.format |
"{:>8}".format(x) |
for templates kept as data |
name, total, ratio = "Ana", 1234.5, 0.0731width, prec = 12, 1print(f"{name!r} {name!s} {'café'!a}")print(f"{total=}", f"{total = :,.2f}", f"{ratio * 100 = :.1f}")print(f"[{total:>{width}.{prec}f}]", f"[{name:^{width}}]", f"{{{name}}}")order = {"id": "O000001", "qty": 3}print(f"{order['id']} x{order['qty']}", f"{len(order)=}")'Ana' Ana 'caf\xe9'total=1234.5 total = 1,234.50 ratio * 100 = 7.3[ 1234.5] [ Ana ] {Ana}O000001 x3 len(order)=2Format-spec mini-language
Section titled “Format-spec mini-language”{value:[[fill]align][sign][z][#][0][width][grouping][.precision][type]}
| Field | Values | Meaning | Example | Result |
|---|---|---|---|---|
| fill | any character | pad character (needs an align) | f"{7:*>4}" |
'***7' |
| align | < > ^ = |
left, right, center, pad after the sign | f"{-7:=5}" |
'- 7' |
| sign | + - space |
always, negatives only (default), space for positives | f"{7:+}", f"{7: }" |
'+7', ' 7' |
z |
z |
show -0.0 as 0.0 (3.11+) |
f"{-0.001:z.1f}" |
'0.0' |
# |
# |
prefix 0x/0o/0b; keep the . with g |
f"{255:#x}" |
'0xff' |
0 |
0 |
zero padding, sign-aware | f"{-7:05}" |
'-0007' |
| width | integer | minimum total width | f"{'ab':5}|" |
'ab |' |
| grouping | , _ |
thousands separator (_ every 4 digits for x, b) |
f"{10**6:_}" |
'1_000_000' |
| precision | .n |
digits after the point (f, e, %), significant digits (g), max chars (s) |
f"{'abcdef':.3}" |
'abc' |
| type | see below | presentation | f"{0.5:%}" |
'50.000000%' |
Default alignment: numbers align right, strings align left.
| Type | For | Meaning | f"{x:...}" |
Result |
|---|---|---|---|---|
s |
str | string (default) | f"{'a':s}" |
'a' |
d |
int | decimal integer | f"{42:d}" |
'42' |
b, o, x, X |
int | binary, octal, hex, upper hex | f"{255:X}" |
'FF' |
c |
int | character for the code point | f"{65:c}" |
'A' |
n |
number | like d/g, with the locale’s separators |
f"{1234:n}" |
'1234' (C locale) |
f, F |
number | fixed point (default precision 6) | f"{2/3:f}" |
'0.666667' |
e, E |
number | scientific | f"{12345.678:.2e}" |
'1.23e+04' |
g, G |
number | general: fixed or scientific, trailing zeros dropped | f"{0.00001234:.3g}" |
'1.23e-05' |
% |
number | times 100, fixed, then % |
f"{0.1234:.1%}" |
'12.3%' |
| none | number | like g, but at least one digit after the point |
f"{1e16}" |
'1e+16' |
x = 1234.5678for spec in ["", ".2f", ",.2f", "_.1f", ">12.2f", "<12.1f", "^12.0f", "*^12,.0f", "012.2f", "+.1f", " .1f", ".3e", ".3g", ".2%", ".0f"]: print(f"{spec!r:12} [{x:{spec}}]")'' [1234.5678]'.2f' [1234.57]',.2f' [1,234.57]'_.1f' [1_234.6]'>12.2f' [ 1234.57]'<12.1f' [1234.6 ]'^12.0f' [ 1235 ]'*^12,.0f' [***1,235****]'012.2f' [000001234.57]'+.1f' [+1234.6]' .1f' [ 1234.6]'.3e' [1.235e+03]'.3g' [1.23e+03]'.2%' [123456.78%]'.0f' [1235]n = 255for spec in ["d", "5d", "05d", "+d", ",d", "b", "08b", "#b", "o", "#o", "x", "#06x", "X", "_b", "c", "<6", "^6", "=+6"]: print(f"{spec!r:7} [{n:{spec}}]")'d' [255]'5d' [ 255]'05d' [00255]'+d' [+255]',d' [255]'b' [11111111]'08b' [11111111]'#b' [0b11111111]'o' [377]'#o' [0o377]'x' [ff]'#06x' [0x00ff]'X' [FF]'_b' [1111_1111]'c' [ÿ]'<6' [255 ]'^6' [ 255 ]'=+6' [+ 255]word, neg = "data", -0.0004for spec in ["", "10", ">10", "^10", "-^10", ".2", ">8.3"]: print(f"{spec!r:7} [{word:{spec}}]")print(f"[{neg:.2f}] [{neg:z.2f}] [{-42:=8}] [{-42:08}] [{42:#010b}]")'' [data]'10' [data ]'>10' [ data]'^10' [ data ]'-^10' [---data---]'.2' [da]'>8.3' [ dat][-0.00] [0.00] [- 42] [-0000042] [0b00101010]Text tables
Section titled “Text tables”rows = [ ("Chicago", 2850, 458.94), ("Minneapolis", 1950, 1234.5), ("Detroit", 1420, 87.0),]print(f"{'city':<12}{'size_sqm':>9}{'revenue':>11}")print("-" * 32)for city, size, revenue in rows: print(f"{city:<12}{size:>9,}{revenue:>11,.2f}")print(f"{'total':<12}{sum(r[1] for r in rows):>9,}{sum(r[2] for r in rows):>11,.2f}")city size_sqm revenue--------------------------------Chicago 2,850 458.94Minneapolis 1,950 1,234.50Detroit 1,420 87.00total 6,220 1,780.44Dates and times in f-strings
Section titled “Dates and times in f-strings”| Code | Meaning | Example (2024-05-01 08:04:09, a Wednesday) |
|---|---|---|
%Y, %y |
year | 2024, 24 |
%m, %d |
month, day (zero-padded) | 05, 01 |
%H, %I, %p |
hour 24h, hour 12h, AM/PM | 08, 08, AM |
%M, %S, %f |
minute, second, microsecond | 04, 09, 000000 |
%a, %A |
weekday short, full | Wed, Wednesday |
%b, %B |
month short, full | May, May |
%j, %U |
day of year, week of year | 122, 17 |
%z, %Z |
UTC offset, zone name | empty for naive datetimes |
%% |
a literal % |
from datetime import datetime
when = datetime(2024, 5, 1, 8, 4, 9)print(f"{when:%Y-%m-%d %H:%M}", f"{when:%a %d %b %Y}", f"{when:%I:%M %p}")print(when.isoformat(), when.strftime("%j"))print(datetime.strptime("01/05/2024", "%d/%m/%Y")) # parse: text -> datetime2024-05-01 08:04 Wed 01 May 2024 08:04 AM2024-05-01T08:04:09 1222024-05-01 00:00:00Other formatting styles
Section titled “Other formatting styles”name, n = "Ana", 3print("%s has %d items, %.1f%%" % (name, n, 12.34)) # printf style (logging uses it)print("{} has {:03d} items".format(name, n)) # str.format: templates kept as dataprint("{name} has {n} items".format_map({"name": name, "n": n}))Ana has 3 items, 12.3%Ana has 003 itemsAna has 3 items| Style | Use it for |
|---|---|
| f-string | almost everything |
str.format / format_map |
templates stored in config or translation files |
% formatting |
logging calls: log.info("loaded %d rows", n) (formats only if the level is on) |
string.Template |
user-supplied templates: Template("Hi $name").substitute(name="Ana") (no code runs) |
Bytes and encodings
Section titled “Bytes and encodings”| Concept | str |
bytes |
|---|---|---|
| holds | Unicode code points | integers 0–255 |
| literal | "café" |
b"caf\xc3\xa9" |
length of café |
4 | 5 in UTF-8 |
| one item | "café"[0] → 'c' |
b"caf"[0] → 99 (an int) |
| convert | s.encode("utf-8") |
b.decode("utf-8") |
| read from a file | open(p, encoding="utf-8") |
open(p, "rb") |
| Encoding | Covers | Note |
|---|---|---|
utf-8 |
all of Unicode, 1–4 bytes per char | the default to choose; ASCII-compatible |
utf-8-sig |
UTF-8 with a BOM | Excel CSV exports; strips the BOM on read |
latin-1 (iso-8859-1) |
256 Western European chars | decodes any bytes without error (maybe wrongly) |
cp1252 |
Windows Western European | like latin-1, plus € and smart quotes |
ascii |
128 chars | fails on any accent |
utf-16 |
all of Unicode, 2 or 4 bytes | some Windows tools |
errors= |
On a bad byte or char | Example result |
|---|---|---|
"strict" (default) |
raise UnicodeDecodeError / UnicodeEncodeError |
|
"replace" |
� on decode, ? on encode |
'caf�' |
"ignore" |
drop it | data loss; avoid |
"backslashreplace" |
\xff escape |
keeps the evidence |
"surrogateescape" |
round-trips unknown bytes | file names, pipes |
text = "Café ☕"data = text.encode("utf-8")print(len(text), len(data), data)print(data.decode("utf-8"), "Café".encode().decode("latin-1")) # wrong codec: mojibakeprint(text.encode("ascii", errors="replace"), b"caf\xff".decode("utf-8", "replace"))print(data[0], data[:3], data.hex(" "), bytes.fromhex("43 61 66"))print(ord("é"), f"U+{ord('é'):04X}", chr(0x2615), "\N{HOT BEVERAGE}" == "☕")6 9 b'Caf\xc3\xa9 \xe2\x98\x95'Café ☕ Caféb'Caf? ?' caf�67 b'Caf' 43 61 66 c3 a9 20 e2 98 95 b'Caf'233 U+00E9 ☕ Truefrom pathlib import Path
raw = Path("data/legacy_latin1.csv").read_bytes()print(raw.decode("latin-1").splitlines()[1]) # the right codecprint(raw.decode("utf-8")) # strict UTF-8 fails on the first non-UTF-8 byteSUP01,Café Müller GmbH,Köln,Germany,2015UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byteUnicode normalization and comparison
Section titled “Unicode normalization and comparison”import unicodedata
composed, decomposed = "é", "e\u0301" # one code point vs. e + combining accentprint(composed == decomposed, len(composed), len(decomposed))print(unicodedata.normalize("NFC", decomposed) == composed)print("Straße".lower(), "Straße".casefold())print("STRASSE".casefold() == "straße".casefold())decomposed_name = unicodedata.normalize("NFD", "José Müller")no_accents = "".join(c for c in decomposed_name if not unicodedata.combining(c))print(no_accents, unicodedata.name("☕"))False 1 2Truestraße strasseTrueJose Muller HOT BEVERAGEGotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| strings are immutable | s.upper() alone changes nothing |
s = s.upper() |
s[0] = "X" |
TypeError: 'str' object does not support item assignment |
"X" + s[1:] |
strip("abc") |
strips any of those characters, not the word | removeprefix / removesuffix |
"".split(",") |
[''], not [] |
s.split(",") if s else [] |
split(" ") vs split() |
"a b".split(" ") → ['a', '', 'b'] |
split() with no argument |
"-".join([1, 2]) |
TypeError: sequence item 0: expected str instance, int found |
"-".join(map(str, xs)) |
s += piece in a big loop |
slow on large text | collect a list, then "".join(parts) |
isdigit() for numbers |
True for "²"; False for "-4" and "4.2" |
try: float(s) |
f"{x:.2f}" on a str |
ValueError: Unknown format code 'f' for object of type 'str' |
convert first: float(x) |
f"{x:,}" with x a Decimal |
works; with a str it fails |
format numbers, not text |
round in specs |
f"{2.675:.2f}" → '2.67' |
Decimal for exact half-up rounding |
0 flag with an align |
f"{7:<05}" → '70000' |
use 0 padding only with right alignment |
!r after the spec |
f"{x:>8!r}" is a ValueError |
conversion first: f"{x!r:>8}" |
| quotes in f-strings before 3.12 | SyntaxError for f"{d["k"]}" |
use the other quote: f"{d['k']}" |
open() without encoding |
platform default (cp1252 on Windows) | always pass encoding="utf-8" |
UnicodeDecodeError on read |
the file is not UTF-8 | try utf-8-sig, cp1252, latin-1; ask the source |
latin-1 “works” on anything |
silent mojibake (Café) |
check a few known values after decoding |
"é" != "é" |
one is NFD (e + accent) | unicodedata.normalize("NFC", s) on input |
lower() for case-insensitive keys |
"Straße".lower() != "STRASSE".lower() |
casefold() |
len() of an emoji |
flags and families count as several code points | len counts code points, not glyphs |
b"abc"[0] |
97, not b'a' |
slice: b"abc"[:1] |
str(b"abc") |
"b'abc'" |
b.decode() |
Learn more
Section titled “Learn more”- 02. Strings and text and its cheat sheet
- 07. Files and data formats for encodings in files
- Files, paths and formats
- Syntax, types and control flow for numbers and rounding