Lesson 10 of 52Collections
Strings Deep Dive
Clean, split, search and rebuild text with string methods, slice with steps, and handle Unicode, raw and multi-line strings.
Real data is messy text: CSV rows with stray spaces, user input in random capitals, log lines you need to pick apart, file paths, URLs. Most of the time you do not need a regex or a library, just the string methods built into Python. String manipulation is also the most common category of warm-up interview question (reverse the words, check a palindrome, count characters).
Cleaning and changing case
Remember: strings are immutable, so every method here returns a new string. The original never changes, which means you must keep the result: name.strip() on its own line does nothing useful.
Press Run (⌘ Enter) to see what happens.repr() shows a string with its quotes and escapes, which makes invisible whitespace visible. Use it whenever you are debugging text.
For case-insensitive comparisons, compare a.casefold() == b.casefold(). casefold is like lower but also handles special cases in other languages, such as the German ß becoming ss.
removeprefix and removesuffix, and the strip trap
Here is a bug that passes code review surprisingly often. You want to drop a file extension or a URL scheme, and strip looks like the tool:
Press Run (⌘ Enter) to see what happens.The argument to strip, lstrip and rstrip is not a substring. It is a set of characters. rstrip(".txt") means "keep removing any of ., t or x from the right until you hit something else", so report.txt loses the extension and then the t of report. lstrip("https://") eats h, t, p, s, : and / from the left, then keeps going into shop because s and h are in the set. The examples above happen to look almost right, which is exactly why the bug survives.
str.removeprefix(p) and str.removesuffix(s) (Python 3.9+) do what people actually mean: remove that exact text once, if it is there, and otherwise return the string unchanged. Reach for them whenever the thing you are removing is a word rather than a set of characters. For file names specifically, pathlib.Path("report.txt").stem is clearer still (see Files and JSON).
What does this print?
print("test_cases.py".lstrip("test_"))
print("test_cases.py".removeprefix("test_"))Splitting and joining
split breaks a string into a list. join does the reverse. Between them they handle most text parsing.
Press Run (⌘ Enter) to see what happens.Two details catch everyone:
split()with no argument splits on any whitespace and drops empties.split(" ")splits on exactly one space and keeps empty strings between repeated spaces.joinis a method of the separator, not of the list:", ".join(items). And every item must already be a string:", ".join(map(str, numbers))for numbers.
What does this print?
print("a,b,,c".split(","))
print("+".join(["x", "y", "z"]))Searching and replacing
Press Run (⌘ Enter) to see what happens.find returns -1 when the text is missing. index does the same search but raises ValueError instead. Use in if you only need yes or no, find if you need the position and missing is normal, and index when missing would be a bug you want to hear about.
There are also handy checks: "42".isdigit(), "abc".isalpha(), "a1".isalnum(), " ".isspace().
"hello".find("z") return?Slicing with steps
Strings slice exactly like lists: s[start:stop:step]. A negative step walks backwards, which gives the most famous Python one-liner: s[::-1] reverses a string.
s[:2] is "PY": start at 0, stop before 2.
What does this print?
s = "abcdefgh" print(s[::3], s[-3:], s[::-2])
Building strings efficiently
Since strings are immutable, result += piece cannot add to the existing string. It builds a new string containing everything so far plus the piece. In a loop, that means copying the growing string again and again: O(n²) work in the worst case.
Press Run (⌘ Enter) to see what happens.CPython has a trick that sometimes makes += fast in place, but it is an implementation detail that other Pythons do not share and that breaks easily. The reliable pattern for building text in a loop is: append pieces to a list, then "".join(parts) at the end.
The format spec mini-language
Numbers and Strings introduced f-string specs like :.2f and :,. Everything after the colon follows one small grammar, and once you can read it you never need to look up a formatting recipe again:
{value!conversion:fill align sign # 0 width grouping .precision type}Every part is optional, and they always come in that order:
- conversion:
!rusesrepr(),!susesstr().!ris the one you want in log and error messages, because it shows quotes and hidden whitespace. - fill and align:
<left,>right,^centre, with an optional fill character before it:{name:*^12}. - sign:
+always shows a sign; a space reserves room for one, so positive and negative numbers line up. #adds a prefix like0xor0b;0pads numbers with zeros.- width is the minimum width; grouping is
,or_for thousands. - precision is digits after the point for
fand%, or significant digits when there is no type. - type:
dinteger,ffixed,escientific,ggeneral,%percentage,x/b/ohex, binary, octal.
Press Run (⌘ Enter) to see what happens.Two details explain the odd cases. First, the spec is handed to the object's __format__ method, which is why a date understands %d %b %Y and a Decimal formats exactly. Your own classes can define __format__ too. Second, the built-in format(value, spec) and str.format use the same grammar, so the skill carries over to templates stored in config files. The aligned table at the end is the everyday payoff: CLI reports and log summaries that line up without any library.
What does this print?
n = 7
print(f"[{n:03}] [{'id':^6}] [{3.14159:.3}]")Unicode, raw strings and multi-line strings
Unicode
A Python str is a sequence of Unicode code points: numbers that identify characters in every writing system. ord turns a character into its code point and chr goes back. When text is saved to a file or sent over a network, it is encoded into bytes, almost always with UTF-8, where one character can take 1 to 4 bytes.
Press Run (⌘ Enter) to see what happens.So len counts code points, not bytes. That matters when a database column or an API limit is measured in bytes.
Raw strings
Backslashes start escape sequences, which is a pain for Windows paths and regular expressions. Prefix the string with r for a raw string, where backslashes are just backslashes.
Press Run (⌘ Enter) to see what happens.Multi-line strings
Triple quotes (""" or ''') let a string span several lines, keeping the newlines. You will see them most as docstrings, the description at the top of a function, in a couple of lessons.
Press Run (⌘ Enter) to see what happens.Unicode normalisation: when equal-looking text is not equal
A customer signs up as café. Later they log in, pasting the name from a PDF, and the lookup fails. Both strings look identical on screen. The problem is that Unicode often has two ways to write the same character: é can be one code point (U+00E9), or a plain e followed by a combining acute accent (U+0301). Python compares code points, so the two strings are not equal and do not even have the same length.
NFC (composed): é is a single code point. len is 4. This is what most keyboards produce.
The fix is to normalise text at the boundary, when it enters your system, with unicodedata.normalize. There are four forms:
- NFC composes characters where possible. It is the right default for storing and comparing text.
- NFD decomposes them. Useful for stripping accents: decompose, then drop the combining marks.
- NFKC and NFKD also fold "compatibility" characters: the ligature
fibecomesfi, full-width letters become normal ones. Use NFKC for identifiers such as usernames, where two visually similar names must not both be allowed. Do not use it on prose you want to keep exactly, because it changes meaning (superscript²becomes2).
For a case-insensitive comparison, combine normalisation with casefold, never with lower:
Press Run (⌘ Enter) to see what happens.The fully correct caseless match
casefold can itself produce text that is no longer normalised, so the Unicode standard's definition of a caseless match is NFD(casefold(NFD(text))), applied to both sides. For identifiers there is a combined form, NFKC_Casefold. In practice "NFC, then casefold" is right for almost all real input, and it is far better than plain == or lower(). Store the normalised form in a separate column (for example email_normalised) with a unique index, and keep the original for display.
Also remember that len counts code points, not what a human sees as one character. A flag or a family emoji is several code points. Counting "user-perceived characters" (grapheme clusters) needs a third-party library; check its docs before relying on it.
a == b is False and len(a) != len(b). What is the most likely cause and fix?str vs bytes
A str is text: a sequence of code points. A bytes object is raw data: a sequence of integers from 0 to 255. Files, sockets, HTTP bodies and subprocess output are all bytes underneath. To cross between them you encode text into bytes and decode bytes into text, always naming the encoding.
Press Run (⌘ Enter) to see what happens.What a senior engineer takes from this:
- Decode at the edges, work in
str, encode at the edges. Mixing the two raisesTypeErrorin Python 3, which is a feature: it stops bugs that Python 2 let through silently. errors=is a decision, not a fix. The default"strict"raises, which is right for data you own."replace"swaps bad bytes for U+FFFD and loses information."backslashreplace"keeps the raw byte values visible, which is ideal for logs."ignore"silently deletes data and almost never belongs in production.latin-1never raises, because every byte maps to some character. That makes it a tempting way to "make the error go away", and the result is mojibake likecafé. Seeingéin data means UTF-8 bytes were decoded as Latin-1 or cp1252 somewhere.
Files and JSON covers the file side: always pass encoding="utf-8" to open. Python 3.15 makes UTF-8 the default, but code that names the encoding behaves the same on every version and platform.
Match each errors= mode to what it does when decoding bad bytes.
Template strings (t-strings)
An f-string is evaluated straight into a finished str. By the time a database driver or an HTML renderer sees it, the values are glued into the text and there is no way to tell which parts came from the user. That is the root of SQL injection and cross-site scripting.
Python 3.14 adds template strings (PEP 750). A t"..." literal has the same syntax as an f-string but produces a string.templatelib.Template, which keeps the static text and the interpolated values separate. A function receiving it can escape, quote or parameterise each value before anything is joined. What Changed in Python 3.11 to 3.15 shows an HTML-escaping example; here is the SQL version, turning a template into a parameterised query:
Press Run (⌘ Enter) to see what happens.Iterating a Template yields the static strings and Interpolation objects in order, skipping empty strings. Each interpolation carries its value, the source expression, and any conversion and format_spec, which are not applied for you: the processing function decides what they mean. A Template deliberately has no rendering __str__, so you cannot pass one where a plain string is expected and get unescaped output by accident.
T-strings are a building block. Expect libraries such as database drivers and HTML and logging tools to accept them over time, but check each library's docs before assuming support. Until then, keep using the driver's own parameter syntax, as Python Security Pitfalls explains.
Match each task to the right tool.
Reverse the words
Write reverse_words(s) that returns the words of s in reverse order, joined by single spaces. Ignore extra spaces anywhere in the input.
reverse_words("hello world") → "world hello"
reverse_words(" lots of space ") → "space of lots"Palindrome sentence
Write is_palindrome(s) that returns True if s reads the same forwards and backwards, ignoring case and anything that is not a letter or digit.
is_palindrome("Racecar") → True
is_palindrome("A man, a plan, a canal: Panama") → True
is_palindrome("hello") → False- split / join
s.split(sep)breaks a string into a list;sep.join(items)glues a list of strings withsepbetween them.- strip
- Returns a copy without whitespace (or given characters) at both ends.
lstrip/rstripdo one side. - find vs index
- Both search for a substring.
findreturns -1 if missing;indexraisesValueError. - s[::-1]
- A slice with step -1: a reversed copy of the string.
- UTF-8
- The standard way to encode Unicode text as bytes; one character takes 1 to 4 bytes.
- raw string
r"...": backslashes are kept literally. Used for Windows paths and regex.- removeprefix / removesuffix
- Remove an exact prefix or suffix once, if present. Unlike
strip, the argument is a substring, not a set of characters. - format spec
- The text after
:in an f-string field: fill, align, sign, width, grouping, precision and type. - Unicode normalisation
- Rewriting text to one canonical form (NFC, NFD, NFKC, NFKD) so equal-looking strings compare equal.
- bytes
- An immutable sequence of integers 0 to 255. Text becomes bytes with
encodeand back withdecode. - t-string
- A
t"..."literal (3.14) that produces aTemplatewith text and values kept separate, for safe escaping.