Strings
A Python string is an immutable sequence of Unicode code points. Every operation that looks like editing a string in fact builds a new one, which is why text-heavy loops need str.join rather than repeated concatenation.
Detailed Explanation
A str holds text, not bytes. Each element is a Unicode code point, and indexing gives you back a one-character string rather than a number or a character type. There is no separate char type in Python, so name[0] is a string of length one.
Internally CPython picks the narrowest storage that fits the widest character in the string, a scheme introduced by PEP 393. A pure-ASCII string stores one byte per character. Add a é and the whole string is re-stored at two bytes per character. Add a character above U+FFFF and it becomes four bytes per character. This is why memory use can jump when one non-ASCII character appears in otherwise plain text, and it is also why len() and indexing stay O(1): every character in a given string occupies the same number of bytes, so position i is direct arithmetic.
Strings are immutable. title[0] = "X" raises TypeError. Methods like .upper(), .replace(), and .strip() return new strings and leave the original untouched. Immutability buys you three things: a string can be a dict key, its hash can be computed once and cached, and passing it around is free because nothing is ever copied defensively.
The cost of immutability is concatenation. Building a 10,000-line report with report += line allocates a new string and copies all the accumulated text on every iteration, so the total work is quadratic. "".join(lines) walks the list once to compute the final length, allocates once, and copies each piece once, which is linear. The exception is worth knowing: when a string has exactly one reference, CPython may resize it in place, so a tight s += x loop sometimes looks linear in practice. Do not rely on it. It disappears the moment a second name touches the string, and it does not exist in PyPy or other implementations.
| Operation | Complexity | Why |
|---|---|---|
text[i], len(text) | O(1) | Fixed width per character, length stored |
text[a:b] | O(k) | Copies k characters into a new string |
a + b | O(n + m) | Allocates and copies both sides |
+= inside a loop | O(n²) overall | A fresh copy per iteration |
"".join(parts) | O(total length) | One allocation, one pass |
needle in text, .find() | O(n) typical, O(n × m) worst | CPython uses a two-way search with a fast skip loop |
.replace(), .split(), .lower() | O(n) | Single pass, new string or list out |
a == b | O(n) | Compares code points, exits early on a mismatch |
hash(text) | O(n) first call, O(1) after | Cached on the object |
.encode("utf-8") | O(n) | Produces a bytes object of possibly different length |
Because they are immutable and interned, short identifier-like literals are often the same object. CPython interns string constants that look like identifiers at compile time, so two occurrences of "user_id" in your source usually share one object. Treat that as an optimisation, never as a rule: compare text with ==, never with is.
One more distinction that trips people up: a code point is not a user-visible character, and it is not a byte. "café" is four code points and five UTF-8 bytes, and the same word typed with a combining accent is five code points that render identically. Normalise with unicodedata.normalize before comparing text that came from different sources.
Code Examples
# Strings are immutable: methods return new strings.
raw_header = " Name: Ana Gupta "
cleaned = raw_header.strip() # new string, original untouched
field = cleaned.removeprefix("Name:").strip() # removeprefix: Python 3.9+
print(field) # Ana Gupta
print(raw_header) # ' Name: Ana Gupta ' unchanged
try:
cleaned[0] = "X"
except TypeError as exc:
print(exc) # 'str' object does not support item assignment
# Building text: join is linear, += in a loop is quadratic.
lines = [f"row {n}" for n in range(5)]
report = ""
for line in lines: # each += copies everything collected so far
report += line + "\n"
report = "\n".join(lines) + "\n" # one allocation, one pass: prefer this
print(report.count("\n")) # 5# Code points are not bytes, and not always what the reader sees.
word = "café"
print(len(word)) # 4 code points
print(len(word.encode("utf-8"))) # 5 bytes: é needs two
import unicodedata
decomposed = "cafe\u0301" # 'e' followed by a combining acute accent
print(len(decomposed)) # 5 <- renders identically, compares unequal
print(word == decomposed) # False
print(word == unicodedata.normalize("NFC", decomposed)) # True
# Slicing and searching.
log_line = "2026-09-12 ERROR disk full"
print(log_line[:10]) # 2026-09-12
print("ERROR" in log_line) # True
print(log_line.split()) # ['2026-09-12', 'ERROR', 'disk', 'full']
print(log_line.split(maxsplit=2)[2]) # disk full <- keep the message intactCommon Gotchas
`+=` in a loop is quadratic
concatenating inside a loop copies the whole accumulated string every iteration, so a large report can take minutes instead of milliseconds. Collect the pieces in a list and call `"".join(pieces)` once.
Never compare strings with `is`
interning makes `"user_id" is "user_id"` return `True` in many cases and `False` when the strings are built at runtime. Use `==`, which compares content.
`len()` counts code points, not bytes or glyphs
database column limits and network protocols count bytes, so validate with `len(text.encode("utf-8"))`. Text from different sources may also need `unicodedata.normalize` before equality checks.
`.strip("abc")` is not a suffix removal
it removes any leading and trailing characters from the set `{a, b, c}`, so `"banana".strip("ba")` gives `"nan"`. Use `removeprefix` and `removesuffix` when you mean an exact affix.