6 Strings
This chapter presents Python’s powerful string facilities and how they underpin everyday text handling. It treats strings as immutable sequences of Unicode characters that support indexing, slicing, and len, and contrasts evaluation versus printing when escape sequences like newlines and tabs are involved. You see basic operators such as concatenation and repetition, practical uses of slicing, and a thorough tour of escape sequences, including octal, hexadecimal, and Unicode escapes (by code point or name). The discussion emphasizes that single characters are still 1-length strings and that operations produce new strings rather than modifying originals.
Building on that foundation, the text surveys the most useful string methods: split and join for tokenizing and assembling text efficiently; strip, lstrip, rstrip plus removeprefix and removesuffix for cleanup; and searching via find/rfind, index/rindex, count, startswith, and endswith. It covers transformation and modification with replace, maketrans/translate, case changing, expandtabs, justification, and zfill, and shows when converting a string to a list (then back) can emulate in-place edits. It also demonstrates converting strings to numbers (including bases), character-class tests (isdigit, isalpha, etc.), and constants from the string module for whitespace, digits, and letters.
The chapter then focuses on turning objects into strings (repr versus str) and modern formatting: the format method with positional/named fields, attribute/element access, and rich specifiers for width, alignment, fill, precision, and type. It introduces f-strings for compact interpolation (including “=”-style debugging) and contrasts both with legacy % formatting (including mapping by name). You also learn practical print options (sep, end, file) and the bytes type—how to encode/decode, and when bytes are appropriate versus text. A final lab ties techniques together for text preprocessing (normalization, punctuation removal, tokenization), highlighting performance-minded choices like building translation tables once and using join instead of repeated concatenation.
Summary
- Python strings have powerful text-processing features, including searching and replacing, trimming characters, and changing case.
- Strings are immutable; they can’t be changed in place.
- Operations that appear to change strings actually return a copy with the changes.
- There are three ways to combine strings and the values of Python expressions: the format method, f-strings, and the legacy method using “%”.
- The format method has an extensive formatting language to control its output.
- F-strings are a very convenient way to create strings containing the values of variables and expressions and are now used widely.
- Python has a bytes data type that contains int’s in the range 0-255; they look similar to strings but need to be decoded to be converted to strings.
FAQ
How are Python strings treated as sequences?
Strings are sequences of characters, so you can index and slice them:x[0], x[-1], x[1:4]. The length is len(x). There is no separate “char” type—x[0] is a 1-character string. Strings are immutable, so operations create new strings instead of modifying in place.What’s a simple way to remove trailing newlines or extra whitespace?
Userstrip() to remove trailing whitespace (including \n), or strip() to remove whitespace from both ends. For example, x = x.rstrip(). You can also pass specific characters: x.strip(",)"). Prefer these over slicing like x[:-1] unless you know exactly what you’re removing.How do split and join work, and why is join preferred over repeated +?
split() breaks a string into a list (default: runs of whitespace). You can provide a delimiter and a maximum number of splits: x.split("::", 1). "sep".join(list_of_strings) builds one string efficiently; it’s preferred over repeated + which creates many temporary strings.How do I convert strings to numbers, and what does the base argument do?
Useint(s) for integers and float(s) for floats. Invalid inputs raise ValueError. int(s, base) parses using the given base (2–36), so digits must be valid for that base (e.g., no “6” in base 6): int("101", 2) == 5, int("ff", 16) == 255.What are escape sequences and how do I include special or Unicode characters?
Common escapes include\n (newline), \t (tab), \\ (backslash), \" and \'. You can use octal (\155) and hex (\x6D) escapes, and Unicode escapes: \u00E1 or by name \N{LATIN SMALL LETTER A WITH ACUTE}. All produce the intended character in the string.Why can a string look different when printed versus evaluated?
At the interactive prompt, evaluating a string shows its representation with escapes (like'a\n\tb'). print() sends characters to the terminal, so escapes are interpreted (newline, tab, etc.) and a newline is appended unless you set end="".How do I search within strings, and what’s the difference between find/index and rfind/rindex?
find(sub[, start[, end]]) returns the first index or -1 if not found. rfind searches from the end. index and rindex are the same but raise ValueError if not found. startswith/endswith return booleans and accept a tuple of prefixes/suffixes.If strings are immutable, how do I “modify” them?
Use methods that return new strings:replace, strip/lstrip/rstrip, removeprefix/removesuffix, upper/lower/title, expandtabs, and translate with maketrans for multi-char mapping or deletions. For list-like edits, convert to a list, mutate, then "".join()—but be mindful of performance.What are the main string formatting options in modern Python?
-str.format() with positional ({0}) and named ({name}) fields, plus format specifiers (width, alignment, precision, fill).- f-strings (
f"...{expr:spec}...") for inline expressions and specs; {expr=} shows “expr=value” for debugging.- Old
%-formatting exists for legacy code but shouldn’t be used in new code.What is the bytes type and how does it differ from str?
str is an immutable sequence of Unicode characters; bytes is a sequence of integers 0–255. Convert with s.encode(...) (str → bytes) and b.decode(...) (bytes → str). You can’t concatenate bytes and str directly. Use bytes for binary data (files, protocols); use str for text.
The Quick Python Book, Fourth Edition ebook for free