Skip to content

02. Strings and text — Cheat sheet

The essentials of module 02 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example → result
count characters len(s) len("S01") → 3
see hidden spaces and line breaks print(repr(s)) or f"{s!r}" print(repr(" N\n")) shows ' N\n'
get the first / last character s[0], s[-1] "S01"[-1] → '1'
get a part by position s[start:stop] "2024-05-09"[5:7] → '05'
reverse a string s[::-1] "abc"[::-1] → 'cba'
test for a substring in "TV" in "Smart TV" → True
find a position s.find(sub) (-1 if absent) "a=b".find("=") → 1
remove spaces at both ends s.strip() " North ".strip() → 'North'
collapse inner spaces " ".join(s.split()) "a b" → 'a b'
remove a known prefix / suffix removeprefix(), removesuffix() "$79.99".removeprefix("$") → '79.99'
replace text s.replace(old, new) "1,299".replace(",", "") → '1299'
delete or swap many characters s.translate(str.maketrans(...)) swap , and . in 1,299.00 → '1.299,00'
fix the case of a label s.strip().title() " NORTH".strip().title() → 'North'
compare ignoring case a.casefold() == b.casefold() "STRASSE" vs "straße" → True
cut at a delimiter s.split(",") "a,b".split(",") → ['a', 'b']
glue pieces together sep.join(pieces) "-".join(["2024", "05"]) → '2024-05'
split once into 3 parts s.partition(sep) "k=v".partition("=") → ('k', '=', 'v')
split a text into lines s.splitlines() "a\nb\n".splitlines() → ['a', 'b']
read a CSV line with quotes csv.reader(lines) handles "$1,299.00"
zero-pad an id f"{n:06d}" or str(n).zfill(6) f"O{51:06d}" → 'O000051'
format money f"{x:,.2f}" 1950934.24 → '1,950,934.24'
format a rate f"{r:.1%}" 0.1926 → '19.3%'
show the sign f"{g:+.1%}" 0.1856 → '+18.6%'
align in a column f"{s:<12}", f"{x:>12,.2f}" text left, numbers right
width from a variable nested spec f"{x:>{w}}"
debug-print a value f"{x=}" f"{total=}" → 'total=458.94'
text → bytes s.encode("utf-8") "é".encode("utf-8") → b'\xc3\xa9'
bytes → text b.decode("utf-8") b"\xc3\xa9".decode("utf-8") → 'é'
read a latin-1 file Path(p).read_text(encoding="latin-1")
fix mojibake s.encode("latin-1").decode("utf-8") ("cp1252" if it shows € or ’) 'Café' → 'Café'
make equal-looking text equal unicodedata.normalize("NFC", s)
make an accent-free search key NFKD + encode("ascii", "ignore") "Malmö" → 'Malmo'
Literal Meaning
'S01', "S01" the same string; pick the quote that the text does not contain
"""...""" multi-line string; keeps the line breaks
r"C:\data\new.csv" raw string: backslashes are literal (paths, regex)
f"{x}" f-string
b"caf\xe9" bytes literal (ASCII characters and \x escapes only)
"a" "b" adjacent literals are joined: 'ab'
Escape Character Escape Character
\n newline \\ backslash
\t tab \', \" quote
\r carriage return (Windows line ends are \r\n) \u00e9 code point U+00E9 (é)
\x41 code point 0x41 (A) \N{EURO SIGN} a character by its Unicode name
print(repr("Line 1\nLine 2\tend"))
print("\N{EURO SIGN}", "\u00e9", "\x41", len("\n"))
print("a" "b", "-" * 5, "ab" + "cd")
Output
'Line 1\nLine 2\tend'
€ é A 1
ab ----- abcd
0 1 2 3 4 5 6
O 0 0 0 0 5 1
-7 -6 -5 -4 -3 -2 -1
Expression s = "O000051" Rule
s[0], s[-1] 'O', '1' first, last
s[7] IndexError indexes run 0 … len(s) - 1
s[1:4] '000' stop is excluded; length = stop - start
s[:3], s[3:] 'O00', '0051' s[:i] + s[i:] == s
s[-3:] '051' last 3
s[:-1] 'O00005' all but the last
s[::2] 'O0001' every 2nd character
s[::-1] '150000O' reversed
s[5:100] '51' slices never raise
ts = "2024-05-09T15:20:00" # fixed positions in ISO timestamps
print(ts[:10], ts[11:16], int(ts[5:7]), int(ts[11:13]))
order_id = "O014877"
print(int(order_id[1:]), f"{order_id[0]}{int(order_id[1:]) + 1:06d}")
Output
2024-05-09 15:20 5 15
14877 O014878

All methods return a new string (or another value). None changes the original: write s = s.strip().

Method "anna-lena O'BRIEN" → Note
lower() "anna-lena o'brien" for display in lower case
upper() "ANNA-LENA O'BRIEN" codes, ids
title() "Anna-Lena O'Brien" new word after any non-letter: Chef'S, 4K Smart Tv
capitalize() "Anna-lena o'brien" first character only
swapcase() "ANNA-LENA o'brien" rarely useful
casefold() "anna-lena o'brien" for comparisons; ß → ss
string.capwords(s) "Anna-lena O'brien" splits on spaces only (needs import string)
Method Does
strip(), lstrip(), rstrip() remove whitespace at both / left / right end
strip("$* ") remove any of these characters at the ends (a set, not a word)
removeprefix(p), removesuffix(s) remove that exact text once, if present
ljust(w), rjust(w), center(w, "=") pad to width w
zfill(w) pad with zeros after a sign: "-7".zfill(4) → '-007'
expandtabs(8) replace tabs with spaces
print(repr(" S01 \n".strip()), repr("$1,299.00".strip("$")))
print("sales_2024.csv".removesuffix(".csv"), "sales_2024.csv".strip(".csv"))
print("[" + "East".center(10, "*") + "]", "51".zfill(6))
Output
'S01' '1,299.00'
sales_2024 ales_2024
[***East***] 000051
Method Returns Note
sub in s bool case-sensitive
s.startswith(x), s.endswith(x) bool x can be a tuple: endswith((".csv", ".txt"))
s.find(sub), s.rfind(sub) index or -1 first / last match
s.index(sub) index raises ValueError if absent
s.count(sub) int non-overlapping matches
isdigit(), isdecimal(), isnumeric() bool False for "21.7" and "-3"
isalpha(), isalnum(), isspace() bool False for ""
isupper(), islower(), istitle() bool ignore characters without case
isascii() bool True for "" too
line = "2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201"
print(line[line.find("[") + 1 : line.find("]")], line.count(" "), line.endswith("201"))
print("2024".isdigit(), "21.7".isdigit(), "Zoë".isalpha(), "Zoë".isascii())
Output
api 7 True
True False True False
print("2023/01/04".replace("/", "-"), "a-b-c".replace("-", "+", 1))
print("1,299.00".translate(str.maketrans(",.", ".,"))) # swap characters
print("Love it!!! Really, great.".translate(str.maketrans("", "", "!,."))) # delete
Output
2023-01-04 a+b-c
1.299,00
Love it Really great
Method "a, b,,c" →
split(",") ['a', ' b', '', 'c'] (empty strings stay)
split() ['a,', 'b,,c'] (on runs of whitespace)
split(",", 1) ['a', ' b,,c'] (at most 1 split)
rsplit(",", 1) ['a, b,', 'c'] (from the right)
partition(",") ('a', ',', ' b,,c')
rpartition(",") ('a, b,', ',', 'c')
messy = " maría josé fernández "
print(messy.split(" "))
print(" ".join(messy.split()))
print(", ".join(["North", "South"]), "|".join("abc"))
print(" ".join(reversed("o'neill, PATRICK".split(", ")))) # last, first -> first last
Output
['', '', 'maría', '', 'josé', '', 'fernández', '']
maría josé fernández
North, South a|b|c
PATRICK o'neill
f"{ expression = !r : format_spec }"
Form Example Result
any expression f"{qty * price:.2f}" computed and formatted
method calls, indexing f"{name.upper()} {ts[:10]}"
!r conversion f"{region!r}" "' North '"
= debug form f"{revenue=:,.0f}" 'revenue=888,229'
literal braces f"{{x}}" '{x}'
nested spec f"{x:>{width}.{dec}f}" width and decimals from variables
several lines (f"..." f"...") in parentheses joined into one string
region, revenue, width = " North ", 888229.47, 14
print(f"{region!r} {region.strip()=} {revenue=:,.0f}")
print(f"[{revenue:>{width},.1f}] {{literal braces}}")
Output
' North ' region.strip()='North' revenue=888,229
[ 888,229.5] {literal braces}
[[fill]align][sign][z][#][0][width][grouping][.precision][type]
Part Options Meaning
fill any character padding character; needs an align
align < > ^ = left (text default), right (number default), center, sign then padding
sign + - space always, negatives only (default), space for positives
z turn -0.00 into 0.00
# alternate form: 0x, 0b, 0o prefixes
0 zero padding after the sign
width number minimum width; never cuts
grouping , _ thousands separator
.precision .2 digits after the point (f, e, %), significant digits (g), max length (strings)
type see below presentation
Type For 1234.5678 → Note
(none) any 1234.5678 like str()
d int — f"{1375:d}" → '1375'
f float 1234.567800 default 6 decimals
e float 1.234568e+03 scientific
g float 1234.57 shortest; 6 significant digits
% float 123456.780000% × 100
s str — default for strings
x X o b int — hex, HEX, octal, binary
c int — the character: f"{233:c}" → 'é'
n number — like d/g with the locale’s separators
Spec Value Shows Use
,.2f 1950934.24 1,950,934.24 money
,.0f 1950934.24 1,950,934 rounded money
.2f with / 1e6 1950934.24 1.95 (add M) millions
, 29533 29,533 counts
_ 29533 29_533 Python-style grouping
.1% 0.1926 19.3% rates, shares
+.1% 0.1856 +18.6% growth
+,.2f -1234.5 -1,234.50 changes
z.2f -0.004 0.00 no negative zero
.3g 3.8423 3.84 significant digits
.2e 0.0000123 1.23e-05 tiny values (p-values); 2 digits after the point
06d 51 000051 ids, file numbers
02d 7 07 dates, clock times
08.2f -3.5 -0003.50 zero-padded decimals
#x 255 0xff hex with prefix
>10 'S01' S01 right-aligned text
*^9 'S01' ***S01*** centered with fill
.10 'Noise-Cancelling Headphones' Noise-Canc cut text
<24.24 a path padded and cut to 24 fixed-width columns
x, rate, growth = 1950934.24, 0.4199624, 0.1855533
print(f"{x:,.2f} | {x:,.0f} | {x / 1e6:.2f}M | {29533:,} | {29533:_}")
print(f"{rate:.1%} | {growth:+.1%} | {-1234.5:+,.2f} | {-0.004:.2f} {-0.004:z.2f}")
print(f"{0.0000123:.2e} | {3.8423:.3g} | {51:06d} | {-3.5:08.2f} | {255:#x} {5:b}")
print(f"[{'S01':>8}] [{'S01':*^9}] [{'Noise-Cancelling Headphones':.10}] [{-42:=6}]")
print(format(x, ",.2f"), "{:>12,.2f}".format(x), "%.1f%%" % 18.6)
Output
1,950,934.24 | 1,950,934 | 1.95M | 29,533 | 29_533
42.0% | +18.6% | -1,234.50 | -0.00 0.00
1.23e-05 | 3.84 | 000051 | -0003.50 | 0xff 101
[ S01] [***S01***] [Noise-Canc] [- 42]
1,950,934.24 1,950,934.24 18.6%
>>> f"{0.125:.2f} {0.375:.2f} {2.675:.2f} {2.5:.0f} {3.5:.0f}"
'0.12 0.38 2.67 2 4'
>>> from decimal import Decimal, ROUND_HALF_UP
>>> Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
Decimal('2.68')
  • Ties go to the even digit; binary floats are often slightly below or above the decimal value you typed.
  • For exact money rounding, use decimal.Decimal built from a string, or whole cents.
rows = "Electronics,1808108.17\nHome,672294.61\nBooks,106908.12"
w_name, w_rev = 12, 16
header = f"{'Category':<{w_name}}{'Revenue (USD)':>{w_rev}}"
print(f"{' Revenue ':=^{len(header)}}")
print(header)
print("-" * len(header))
for row in rows.splitlines():
name, value = row.split(",")
print(f"{name:<{w_name}}{float(value):>{w_rev},.2f}")
Output
========= Revenue ==========
Category Revenue (USD)
----------------------------
Electronics 1,808,108.17
Home 672,294.61
Books 106,908.12
Rule Why
text <, numbers > decimal points line up
header uses the same widths and alignments as the rows the columns stay straight
widths in variables; nested specs change a width once
width ≥ longest value the width is a minimum, so long values push the line
"-" * len(header) a separator exactly as wide as the table
NFC before formatting width counts code points; NFD accents shrink a row
Style Example When
f-string f"{name}: {x:,.2f}" default choice
str.format() "{}: {:,.2f}".format(name, x) templates defined before the values exist
named fields "{region}: {rev:,.0f}".format(region="West", rev=822844.57) templates in config files
format() format(x, ",.2f") apply one spec
% "%s: %.2f" % (name, x) old code, logging messages
Concept Python Example
code point of a character ord(c) ord("é") → 233
character of a code point chr(n) chr(8364) → '€'
Unicode name unicodedata.name(c) 'LATIN SMALL LETTER E WITH ACUTE'
text → bytes s.encode(enc) "Köln".encode("utf-8") → b'K\xc3\xb6ln'
bytes → text b.decode(enc) b'K\xf6ln'.decode("latin-1") → 'Köln'
bytes as numbers list(b) list(b"Ab") → [65, 98]
read a file as bytes Path(p).read_bytes()
read / write text Path(p).read_text(encoding=...), write_text(s, encoding=...) always name the encoding
city = "Köln"
print(len(city), len(city.encode("utf-8")), len(city.encode("latin-1")))
print(city.encode("utf-8"), city.encode("latin-1"), list("ö".encode("utf-8")))
print(ord("é"), chr(233), f"U+{ord('€'):04X}", "€".encode("utf-8"))
Output
4 5 4
b'K\xc3\xb6ln' b'K\xf6ln' [195, 182]
233 é U+20AC b'\xe2\x82\xac'
Encoding Bytes per character Covers Notes
ascii 1 128 characters English letters, digits, punctuation
utf-8 1–4 all of Unicode the default to use everywhere
utf-8-sig 1–4 all of Unicode UTF-8 that skips (reading) or writes a BOM; Excel “CSV UTF-8”
latin-1 (iso-8859-1) 1 256 characters legacy Western Europe; never fails to decode
cp1252 1 latin-1 plus €, curly quotes Windows default in many old exports
utf-16 2 or 4 all of Unicode some Windows and Excel exports; starts with a BOM
errors= Encode Decode
"strict" (default) raises UnicodeEncodeError raises UnicodeDecodeError
"replace" ? for each bad character � (U+FFFD) for each bad byte
"ignore" drops the character drops the byte
"backslashreplace" \xe9-style escapes \xe9-style escapes
latin1 = "Café".encode("latin-1")
print(latin1.decode("utf-8", "replace"), latin1.decode("utf-8", "backslashreplace"))
print("Łukasz".encode("ascii", "replace"), "Łukasz".encode("ascii", "ignore"))
garbled = "Café Müller".encode().decode("latin-1") # encode() defaults to UTF-8
print(garbled, "->", garbled.encode("latin-1").decode("utf-8"))
with_bom = b"\xef\xbb\xbfid,name" # a UTF-8 BOM, then the header
print(repr(with_bom.decode("utf-8")), with_bom.decode("utf-8-sig"))
Output
Caf� Caf\xe9
b'?ukasz' b'ukasz'
Café Müller -> Café Müller
'\ufeffid,name' id,name
Symptom Cause Fix
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 file is latin-1 / cp1252 encoding="latin-1" or "cp1252"
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0141' text has characters the target encoding lacks write UTF-8 instead
Café, ’ (mojibake) UTF-8 decoded as latin-1 / cp1252 s.encode("cp1252").decode("utf-8") when the text has €, ™ or ’; else "latin-1" works too
� in text decoded with errors="replace" re-read the raw bytes with the right encoding
'\ufeffid' as the first column name UTF-8 BOM encoding="utf-8-sig"
TypeError: can't concat str to bytes mixing str and bytes decode or encode first
Form Does Use
NFC compose: e + ◌́ → é storage, comparison, display (default choice)
NFD decompose: é → e + ◌́ removing accents (with a filter)
NFKC compose + replace compatibility characters (fi → fi, ² → 2) search, user input
NFKD decompose + compatibility accent-free keys
import unicodedata
nfd = "Jose\u0301" # e + combining acute accent
print(nfd == "José", unicodedata.normalize("NFC", nfd) == "José", len(nfd))
print(unicodedata.normalize("NFKC", "file 12 m²"))
key = unicodedata.normalize("NFKD", "São Paulo, Malmö, Søren").encode("ascii", "ignore")
print(key.decode().casefold()) # ø has no decomposition: it is dropped
Output
False True 5
file 12 m2
sao paulo, malmo, sren
Problem Recipe
unknown encoding read bytes; try utf-8, then cp1252 / latin-1; check known names
NFD accents unicodedata.normalize("NFC", s)
spaces at the ends s.strip()
repeated spaces, tabs, line breaks inside " ".join(s.split())
label case s.title() (regions, people’s names)
comparison key " ".join(s.split()).casefold()
accent-free key unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
"last, first" " ".join(reversed(s.split(", ")))
price text "$1,299.00" float(s.removeprefix("$").replace(",", ""))
missing tokens "", "N/A", "-" treat as missing (None), never as a category
product or brand names collapse spaces; keep the case; match against the official list
punctuation s.translate(str.maketrans("", "", string.punctuation))
from pathlib import Path
raw = Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines()
clean = []
for name in raw:
name = " ".join(unicodedata.normalize("NFC", name).split())
clean.append(" ".join(reversed(name.split(", "))).title())
print(clean[0], "|", clean[18], "|", len(raw), "->", len(set(clean)), "distinct")
Output
José García | Patrick O'Neill | 20 -> 18 distinct
Error (last traceback line) Typical cause Fix
IndexError: string index out of range s[len(s)] or an index on "" last index is -1; check len() first
TypeError: 'str' object does not support item assignment s[0] = "P" s = "P" + s[1:]
TypeError: can only concatenate str (not "int") to str "Units: " + 5 f-string
ValueError: could not convert string to float: '$59.99' currency sign or separator removeprefix("$"), replace(",", "")
ValueError: substring not found s.index(sub) with no match find() and test for -1
ValueError: Unknown format code 'd' for object of type 'float' f"{2.5:d}" :.0f, or convert with int()
ValueError: Invalid format specifier '.2f,' for object of type 'int' parts in the wrong order, e.g. :.2f, [[fill]align][sign]...[width][,][.precision][type]
UnicodeDecodeError: 'utf-8' codec can't decode byte ... wrong encoding name the right encoding
UnicodeEncodeError: 'ascii' codec can't encode character ... writing non-ASCII text with an ASCII encoding encoding="utf-8"
print(f"{1375:>8,d} {1375.0:>8,.0f}")
print(f"{2.5:d}")
Output
1,375 1,375
ValueError: Unknown format code 'd' for object of type 'float'
  • Strings are immutable. s.strip() alone does nothing useful; write s = s.strip().
  • The stop index of a slice is excluded: ts[11:13] is the 2-digit hour.
  • strip(".csv") strips a set of characters. Use removesuffix(".csv").
  • split(" ") keeps empty strings; split() does not.
  • split(",") breaks on quoted CSV fields. Use the csv module.
  • "21.7".isdigit() and "-3".isdigit() are False. Test numbers with float() in try (module 06).
  • title() gives Chef'S and Smart Tv. Do not use it on product names.
  • Comparisons are case-sensitive and by code point: "Zoë" < "anna" and "S10" < "S9" are True. Use key=str.casefold and zero-padded ids.
  • The % format type multiplies by 100. Store rates as fractions.
  • f"{2.675:.2f}" is 2.67. Ties round to even, and floats are binary.
  • A format width is a minimum. Long values push the line; precision (.10) cuts text.
  • Sign after align: :>+10.1f, not :+>10.1f (that makes + the fill character).
  • Width counts code points, not screen columns: normalize to NFC before formatting.
  • str and bytes never mix. Encode or decode explicitly.
  • Always pass encoding= when you read or write text files.
  • latin-1 never fails to decode, so a wrong guess gives silent mojibake. Check known names.
  • errors="ignore" and errors="replace" hide data loss. Use them to inspect, not in pipelines.
  • "José" == "José" can be False (NFC vs NFD). Normalize first.
  • ASCII keys drop ø, ł, ð, ı. Use them for matching only, never as stored values.