Code Reference

Strings

Python · Reference cheat sheet

Strings

Python · Reference cheat sheet


📋 Overview

str is an immutable sequence of Unicode code points. Build strings with f-strings, join, and methods like split/strip/replace. Prefer methods and the str API over manual index loops. For binary data use bytes / bytearray.

🔧 Core concepts

Literals / access

AreaNotes
Literals'...', "...", '''...''', """...""", raw r"...", f-strings
ImmutabilityMethods return new strings
Index / slices[0], s[-1], s[1:4], s[::-1]
Encodes.encode("utf-8"), b.decode("utf-8")

Search / test

MethodNotes
in / find / rfindSubstring; find → −1 if missing
index / rindexLike find; raises ValueError
startswith / endswithPrefix/suffix; tuple of options ok
count(sub[, start[, end]])Non-overlapping count
isalnum / isalpha / isdigit / isdecimal / isnumericCharacter class tests
islower / isupper / istitle / isspace / isidentifier / isprintableMore predicates

Case / strip / pad / align

MethodNotes
lower / upper / title / capitalize / swapcaseCase transforms
casefold()Aggressive caseless matching
strip / lstrip / rstripTrim chars (default whitespace)
removeprefix / removesuffixExact affix remove (3.9+)
center / ljust / rjust / zfillPad / zero-pad

Split / join / partition / replace

MethodNotes
split(sep=None, maxsplit=-1)None collapses whitespace
rsplit / splitlines(keepends=False)From right; by line breaks
partition / rpartition(before, sep, after)
",".join(parts)Join iterable of str
replace(old, new, count=-1)Replace occurrences
translate(table) / maketransChar mapping (fast multi-replace)
format / format_map / f-stringsInterpolation

Multiline strings keep newlines; use textwrap.dedent for indented source blocks.

💡 Examples

Clean and split:

raw = "  Ada, Bob, Cary  "
names = [p.strip() for p in raw.split(",")]
print(names)  # ['Ada', 'Bob', 'Cary']
print(", ".join(names))

Checks and replace:

path = "Report.PDF"
print(path.lower().endswith(".pdf"))
print(path.removesuffix(".PDF") + ".pdf")  # 3.9+

Slicing and membership:

s = "python"
print(s[1:4])      # yth
print("th" in s)   # True
print(s[::-1])     # nohtyp

Bytes boundary:

text = "café"
data = text.encode("utf-8")
print(data)                 # b'caf\xc3\xa9'
print(data.decode("utf-8"))

⚠️ Pitfalls

  • str is immutable—s[0] = "X" is illegal; build a new string.
  • + in a loop is quadratic for large joins—use "".join(parts).
  • Default split() collapses whitespace; split(" ") does not.
  • Comparing with == is case-sensitive; normalize with casefold() for caseless match.
  • Mixing str and bytes raises TypeError—decode/encode explicitly.

On this page