Python cheat sheet: strings, lists, dicts and f-strings
The everyday methods for text, lists and dictionaries, plus f-string formatting and comprehensions, each with a one-line example you can paste into a Python shell.
This page collects the operations you reach for every day. Strings are immutable, so string methods return a new string and leave the original alone. Lists and dicts are mutable: most of their methods change the object in place and return None. Keeping that difference in mind prevents a whole class of bugs.
f-strings
name, price, ratio, count = "Ada", 1234.5678, 0.256, 7
f"Hi {name}!" # 'Hi Ada!'
f"{price:.2f}" # '1234.57' two decimals
f"{price:,.2f}" # '1,234.57' thousands separator
f"{ratio:.1%}" # '25.6%' percentage
f"{count:03d}" # '007' zero padding
f"[{name:>8}]" # '[ Ada]' right align in 8 chars
f"[{name:<8}]" # '[Ada ]' left align
f"[{name:^8}]" # '[ Ada ]' center
f"{255:x} {255:b}" # 'ff 11111111' hex and binary
f"{count=}" # 'count=7' handy for debugging
f"{name!r}" # "'Ada'" use repr()
Strings
s = " Hello, World "
s.strip() # 'Hello, World' (also lstrip / rstrip)
s.lower(), s.upper() # change case
"hello world".title() # 'Hello World'
"a,b,,c".split(",") # ['a', 'b', '', 'c']
"one two three".split() # ['one', 'two', 'three'] any whitespace
"-".join(["a", "b", "c"]) # 'a-b-c'
"hello".replace("l", "L") # 'heLLo'
"hello".startswith("he") # True (also endswith)
"ell" in "hello" # True
"hello".find("z") # -1 (index() raises ValueError instead)
"report.csv".removesuffix(".csv") # 'report'
"v1.2".removeprefix("v") # '1.2'
"42".isdigit() # True
"7".zfill(3) # '007'
Lists
nums = [3, 1, 2]
nums.append(4) # add one item to the end
nums.extend([5, 6]) # add many items
nums.insert(0, 0) # insert at a position
nums.pop() # remove and return the last item
nums.remove(3) # remove the first matching value
nums.sort() # sorts in place, returns None
sorted(nums, reverse=True) # returns a NEW sorted list
nums[-1], nums[1:3], nums[::-1] # last item, slice, reversed copy
len(nums), sum(nums), min(nums), max(nums)
nums.index(2), nums.count(2)
for i, item in enumerate(["a", "b"], start=1):
print(i, item)
list(zip(["a", "b"], [1, 2])) # [('a', 1), ('b', 2)]
Dictionaries
ages = {"ana": 34, "ben": 28}
ages["cy"] = 41 # add or overwrite
ages.get("zoe") # None instead of KeyError
ages.get("zoe", 0) # 0 as a default
ages.update({"ben": 29}) # merge another dict in
ages.pop("cy") # remove and return the value
ages.setdefault("dan", 0) # set only if the key is missing
"ana" in ages # checks keys
merged = ages | {"eve": 50} # new merged dict
for key, value in ages.items():
print(key, value)
Comprehensions
A comprehension builds a new collection from an existing one in a single expression. Read it as “give me this for each item, if the condition holds”.
[n * n for n in range(5)] # [0, 1, 4, 9, 16]
[n for n in range(10) if n % 2 == 0] # even numbers
{w: len(w) for w in ["apple", "kiwi"]} # {'apple': 5, 'kiwi': 4}
{c.lower() for c in "AaBb"} # set: {'a', 'b'}
sum(n * n for n in range(5)) # generator, no list built
If a comprehension needs more than one if or nested loops, a normal for loop is usually easier to read.
Sorting by a key
sorted(["bob", "Al", "cy"], key=str.lower) # case-insensitive
sorted(ages.items(), key=lambda kv: kv[1], reverse=True) # dict by value
Common traps
result = my_list.sort()setsresulttoNone. Usesorted(my_list)when you need the value.s.replace(...)does nothing tositself; assign the result:s = s.replace(...).d["missing"]raisesKeyError; used.get("missing")when a key may be absent.removeprefixandremovesuffixremove an exact text;strip("xyz")removes any of those characters from both ends.
See also
- 0005 Dataclasses in depth @dataclass writes __init__, __repr__ and __eq__ for classes that mainly hold data. Learn defaults, default_factory, frozen and ordered classes, __post_init__ validation, slots… Advanced · Concept · Any system Article Basics 15 Oct 2026
History
Every saved edit is kept. The plot on the sleeve draws one line per edit. Open any edit to see exactly what changed.
- commitpedia-admin +4,913 chars