Python · Chapter 6 of 21
Python strings: cleaning, searching, regex and f-strings
13 min study · Examples checked with Python 3.14 and 3.15 ·
Most data enters a program as text: form fields, file lines, URLs, API responses. Before you can use it, you usually clean it (remove stray spaces, split it into parts), search it, and finally present results in a readable format. This chapter covers those three steps with string methods, the re module for patterns, and f-strings for output.
Strings are immutable Unicode text
A str is a sequence of Unicode characters. Indexing and slicing work as with lists, and every operation that seems to change a string actually returns a new one.
title = "Python café"
print(title[0], title[-1], title[:6]) # P é Python
print(len(title)) # 11
data = title.encode("utf-8")
print(data) # b'Python caf\xc3\xa9'
print(len(data), data.decode("utf-8") == title) # 12 True
shout = title.upper()
print(title, "|", shout) # Python café | PYTHON CAFÉ
Text (str) and bytes (bytes) are different types. Files, sockets and HTTP carry bytes; your program should work with str and convert at those boundaries with encode and decode, naming the encoding (UTF-8 almost always). Here é is one character but two bytes in UTF-8. Note also that len counts code points, not what a reader sees as characters: some emoji and accented letters are built from several code points.
Because strings are immutable, title.upper() leaves title alone. Forgetting to keep the result, as in title.strip() on a line by itself, is a common bug that does nothing at all.
Literals, escapes and raw strings
Strings can use single or double quotes. Triple quotes span several lines. A backslash starts an escape sequence: \n is a newline, \t a tab, \\ a literal backslash.
message = 'She said "hi"\nand left.'
print(message)
path = r"C:\new\tests" # raw string: backslashes stay as typed
print(path, len(path)) # C:\new\tests 12
note = """First line
second line"""
print(note.splitlines()) # ['First line', 'second line']
print("Py" "thon") # Python (adjacent literals are joined)
A raw string (r"...") turns off escape processing, which is what you want for Windows paths and regular expressions. Without the r, "C:\new" would contain a newline.
Clean input: strip, split and join
raw = " Python, FastAPI,, Django \n"
parts = [p.strip() for p in raw.split(",")]
topics = [p for p in parts if p]
print(parts) # ['Python', 'FastAPI', '', 'Django']
print(topics) # ['Python', 'FastAPI', 'Django']
print(" / ".join(topics)) # Python / FastAPI / Django
print("a b\n c".split()) # ['a', 'b', 'c']
print("report.txt".removesuffix(".txt")) # report
print("txt.report.txt".strip(".txt")) # repor
split() with no argument splits on any run of whitespace and drops empty pieces. With an explicit separator it keeps empty fields, which matters when an empty field means something (a blank column in a CSV line, say). join is the reverse: it is called on the separator and takes an iterable of strings.
strip, lstrip and rstrip remove characters, not a substring: strip(".txt") removes any of ., t and x from both ends, which is why the last line ate the leading txt. and even the final t of report. To remove an exact prefix or suffix, use removeprefix and removesuffix.
How much to clean depends on the field. Trimming spaces from a course title is fine; trimming a password is not. When you need a normalized form only for comparison, keep the original for display.
Search and compare text
titles = ["Python Basics", "FastAPI Requests", "Django Models"]
query = "PYTHON"
print([t for t in titles if query.casefold() in t.casefold()]) # ['Python Basics']
text = "python/python"
print(text.find("/"), text.find("ruby")) # 6 -1
print(text.count("python"), text.startswith(("py", "Py"))) # 2 True
print(text.replace("python", "Py", 1)) # Py/python
print("Straße".lower(), "Straße".casefold()) # straße strasse
in answers “does it occur?”. find returns the position or -1; index does the same but raises ValueError when there is no match. Never write if text.find(x):, because a match at position 0 is false and “not found” (-1) is true. startswith and endswith accept a tuple of options.
For case-insensitive comparison use casefold, which handles more languages than lower (German ß becomes ss). Accented letters can also be stored in two forms, one code point or a letter plus a combining accent; unicodedata.normalize("NFC", s) brings both to the same form before comparing.
Find patterns with regular expressions
String methods handle fixed text. When you need a pattern (“a course code: two letters, a dash, three digits”), use the re module:
import re
log = "Enrolled PY-101 on 2026-11-02; moved to DJ-205 on 2026-11-09."
codes = re.findall(r"\b[A-Z]{2}-\d{3}\b", log)
print(codes) # ['PY-101', 'DJ-205']
date = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})")
first = date.search(log)
print(first.group("month"), first.span()) # 11 (19, 29)
print(date.sub(r"\g<day>.\g<month>.\g<year>", log))
# Enrolled PY-101 on 02.11.2026; moved to DJ-205 on 09.11.2026.
print(bool(re.fullmatch(r"\d{4}", "2026")), re.split(r"[;,]\s*", "a, b;c"))
# True ['a', 'b', 'c']
The core syntax: \d is a digit, \w a word character, \s whitespace, \b a word boundary, [A-Z] a character class, {2} an exact count, + one or more, * zero or more, ? optional, and ( ) a group ((?P<name>...) names it). search finds the first match anywhere, fullmatch requires the whole string to match, findall returns all matches, sub replaces them, and split splits on a pattern. search returns None when there is no match, so check before calling .group().
Always write patterns as raw strings, and compile a pattern you use repeatedly. Regular expressions are a validation tool, but a limited one: a pattern can check that a date looks like YYYY-MM-DD, not that February 30 doesn’t exist. For that, parse the value (chapter 17).
Format output with f-strings
An f-string evaluates the expressions in braces. After a colon you can add a format specification: alignment, width, precision and number style.
name, done, total = "Ada", 7, 12
price = 1234.5
print(f"{name}: {done}/{total} ({done / total:.1%})") # Ada: 7/12 (58.3%)
print(f"{price:,.2f} | {price:>12.1f} | {42:08b}")
# 1,234.50 | 1234.5 | 00101010
print(f"[{name:<6}] [{name:^7}] [{name:>6}]") # [Ada ] [ Ada ] [ Ada]
print(f"Chapter {3:02}") # Chapter 03
print(f"{done=}, {total - done = }") # done=7, total - done = 5
<, ^ and > align left, centre and right within a width. .2f fixes two decimals, , adds thousands separators, % multiplies by 100 and adds a percent sign, and b, x or o print binary, hex or octal. The = form prints the expression next to its value, which is handy for quick debugging. str.format and the older % operator use the same ideas; you will see them in existing code.
Formatting does not make text safe for another language. Inserting user input into HTML needs HTML escaping, and inserting it into SQL needs parameters, never an f-string. Python 3.14 added template strings (t"..."), which keep the parts separate so a library can escape them; they are worth knowing when you meet a library that accepts them.
Practice
Take the line " py-101, DJ-205 ,, xx-1, FA-310 ". Split it into codes, strip spaces, drop empty items, uppercase them, and keep only codes that match two letters, a dash and three digits. Print each with a two-digit position number, like 01. PY-101.
Answer check: three codes survive: PY-101, DJ-205 and FA-310; XX-1 fails the pattern. Use re.fullmatch rather than re.search, otherwise a value such as PY-1012 would pass because it contains a match.
Summary
Strings are immutable Unicode; bytes are for files and networks. Clean with strip, split and join, remove exact affixes with removeprefix/removesuffix, compare with casefold, and never treat find as a boolean. Use re for patterns, with raw strings and fullmatch for validation, and f-string format specs for output.