Strings cheatsheet.

f-strings (PEP 498/701)

name = "Alice"
age = 30

f"Hello {name}"
f"Age: {age}"
f"{age + 1}"
f"{name!r}"               # repr: 'Alice'
f"{name!s}"               # str (default)
f"{name!a}"               # ascii: 'Alice'

# Format spec
f"{age:5d}"               # right-aligned width 5
f"{age:05d}"              # zero-padded
f"{3.14159:.2f}"          # 2 decimal places
f"{1234567:,}"            # 1,234,567
f"{0.5:.1%}"              # "50.0%"
f"{42:b}"                 # binary: "101010"
f"{255:x}"                # hex: "ff"
f"{255:X}"                # HEX: "FF"
f"{255:08b}"              # zero-pad binary

# Alignment
f"{name:<10}"             # left-align width 10
f"{name:>10}"             # right
f"{name:^10}"             # center
f"{name:*^10}"            # center with fill char *

Multiline f-string (3.12+ allows complex)

msg = f"""
Hello {name},
You are {age} years old.
"""

# Expressions in f-strings can be multiline (3.12+):
f"{
    some + complex
    + expression
}"

Debug f-string (3.8+)

print(f"{name=}")         # name='Alice'
print(f"{age=}, {name=!r}")

str methods

s = "  Hello World  "

s.lower()
s.upper()
s.title()                 # "Hello World"
s.capitalize()
s.swapcase()
s.casefold()              # aggressive lowercasing (unicode)

s.strip()
s.lstrip()
s.rstrip()
s.strip(",.")             # strip specific chars

s.startswith("He")
s.endswith("ld")

"o" in s
s.count("o")
s.find("o")               # -1 if not found
s.rfind("o")
s.index("o")              # raises if not found

s.replace("World", "Python")
s.replace("a", "b", 1)    # only first

s.split()                 # by whitespace
s.split(",")
s.rsplit(",", 1)          # last comma only
s.splitlines()            # by \n, \r\n, etc

",".join(["a", "b", "c"])

s.center(20, "*")
s.ljust(20)
s.rjust(20)
s.zfill(5)                # zero-pad

s.isdigit()
s.isalpha()
s.isalnum()
s.isspace()
s.isupper()
s.islower()

Slicing

s = "hello"
s[0]                      # "h"
s[-1]                     # "o"
s[1:4]                    # "ell"
s[:3]                     # "hel"
s[3:]                     # "lo"
s[::-1]                   # "olleh" reverse
s[::2]                    # "hlo" every 2nd

Concatenation

# OK for few
a + b + c

# For loop: use list + join (faster)
parts = []
for x in items:
    parts.append(str(x))
result = ",".join(parts)

# OR generator with join
result = ",".join(str(x) for x in items)

str ↔ bytes

s = "hello"
b = s.encode("utf-8")     # b"hello"
back = b.decode("utf-8")

# Errors
b.decode("utf-8", errors="ignore")
b.decode("utf-8", errors="replace")   # ? for bad bytes

Hex / base64

import binascii

bytes.fromhex("48656c6c6f")
b"Hello".hex()                  # "48656c6c6f"

import base64
b64 = base64.b64encode(b"data")
original = base64.b64decode(b64)

# URL-safe
base64.urlsafe_b64encode(b"data")

Unicode

import unicodedata

unicodedata.normalize("NFC", "café")    # composed
unicodedata.normalize("NFD", "café")    # decomposed

# Strip accents
def strip_accents(s):
    nfd = unicodedata.normalize("NFD", s)
    return "".join(c for c in nfd if unicodedata.category(c) != "Mn")

Templates (Template strings)

from string import Template

t = Template("Hello $name, you are $age")
t.substitute(name="Alice", age=30)
t.safe_substitute(name="Alice")    # missing → "$age"

printf-style %

"Hello %s, %d years" % ("Alice", 30)

Old style; f-strings are preferred.

.format()

"Hello {}, {} years".format("Alice", 30)
"Hello {name}, {age} years".format(name="Alice", age=30)

Old style; f-strings are preferred.

Common patterns

# Pluralize
def plural(count, singular, plural):
    return f"{count} {singular if count == 1 else plural}"

# Truncate
def truncate(s, n):
    return s[:n] + "..." if len(s) > n else s

# Title case (words capitalized)
"hello world".title()                # "Hello World"

# Word count
len("hello world".split())

# Reverse words
" ".join(reversed("hello world".split()))

Regex via re

import re

# Match
re.match(r"^\d+$", s)        # at start
re.search(r"\d+", s)         # anywhere
re.fullmatch(r"\d+", s)

# Find all
re.findall(r"\d+", s)
re.finditer(r"\d+", s)

# Replace
re.sub(r"\s+", " ", s)
re.sub(r"(\d+)", r"<\1>", s)  # backrefs

# Compile
PATTERN = re.compile(r"...")
PATTERN.search(s)

Common mistakes

  • + concatenation in loop — O(n²). Use list + join.
  • Forgetting encoding when reading bytes — UnicodeDecodeError.
  • Mixing str and bytes — TypeError.
  • Regex without re.compile for repeated use.

Read this next

If you want my string utilities collection, it’s at rajpoot.dev .


Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .