Python strings are immutable Unicode sequences. Slice with s[start:stop:step], build with f-strings, and split/join for CSV-like data. None, 0, "", and [] are falsy. Distinguish str (text) from bytes (raw) — decode with an explicit encoding, usually UTF-8.
This Python cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Slice:
s[0:3],s[-1],s[::-1]reverse. End index is exclusive. - split/join:
s.split(",")and",".join(parts)— join needs strings. - strip:
strip,lstrip,rstripfor whitespace or given chars. - find:
in,startswith,endswith,s.find(-1 if missing) orindex(throws). - replace:
s.replace("a", "b")returns a new string. Count is optional. - f-string:
f"{price:.2f}",f"{name:>10}"alignment. - bytes:
b"abc",s.encode("utf-8"),b.decode("utf-8"). - bool:
bool("")is False. Do not useorfor0if zero is valid — useis None.
Copy-paste examples
Slug, initials, and money format
f-strings are the default in new code. Avoid % formatting unless matching an old codebase.
def slugify(title: str) -> str:
keep = []
for ch in title.strip().lower():
if ch.isalnum():
keep.append(ch)
elif ch.isspace() or ch in '-_':
keep.append('-')
return ''.join(keep).strip('-')
def initials(name: str) -> str:
parts = [p[0] for p in name.split() if p]
return ''.join(parts).upper()
def money(n: float) -> str:
return f'${n:,.2f}'Common mistakes
- Treating user input as bytes and concatenating to
str(TypeError). isto compare strings (s is "hi") instead of==.- Using
%sinterpolation with untrusted data in SQL — that is not parameterization. - Assuming
len(s)is the number of graphemes for emoji-heavy text.
FAQ
- str vs repr?
stris readable.repris unambiguous for debugging. f-strings usestrunless you use!r.
- Why is BLOGPH0 returning BLOGPH1 ?
orreturns the first truthy value. Zero is falsy. Use an explicitNonecheck for numbers.
- Multiline strings? Triple quotes
"""...""". Watch accidental indent in the string body.
Related Python cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.