Python Strings
Tutorial 7 of 65 · pythondeck.com Python course
Strings are immutable sequences of Unicode characters. They support slicing, concatenation, formatting and a rich set of methods like split, join, strip, replace, startswith, format. Use f-strings for fast, readable interpolation.
Strings represent text as immutable sequences of Unicode code points. Most programs read, format, split, and validate strings from users, files, and networks.
Mastering strings means understanding encoding (bytes vs str), slicing, and modern formatting with f-strings so you avoid brittle concatenation and deprecated patterns.
Literals: 'single', "double", triple quotes for multiline docstrings.
Strings are immutable; methods return new strings (.strip(), .replace()).
Indexing and slicing: s[0], s[-1], s[1:4], s[::2].
f-strings: f"{name!r} has {n} items" evaluate expressions at runtime.
str vs bytes: encode/decode with .encode("utf-8") / .decode().
Useful methods: split, join, startswith, find, casefold for comparisons.
Raw strings r"\n" keep backslashes literal—common for regex patterns. Normalized Unicode comparison may require unicodedata.normalize for user-facing search.
Large text builds should use io.StringIO or join a list of fragments, not repeated += in tight loops (though CPython optimizes some cases).
Regular expressions live in re; use them when split/strip is insufficient. Path strings are still str—pathlib.Path stringify cleanly for legacy APIs.
Mutating a string in place (impossible)—you must rebind: s = s + "x".
Default-encoding files on Windows without specifying encoding="utf-8" in open().
Using + to build SQL or HTML without escaping (injection risk).
Assuming len(s) counts characters in all languages (grapheme clusters can differ).
Always pass encoding="utf-8" when reading and writing text files.
Prefer f-strings or str.format over old % formatting unless required.
Use pathlib.Path for paths instead of manual string joins.
Validate and normalize user text before persistence; store UTF-8 in databases.
Prefer removeprefix and removesuffix (3.9+) over brittle slice math on prefixes.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates slicing. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Slicing
# Run in the REPL or save as a .py file and execute with python.
s = "PythonDeck"
print(s[0:6]) # Python
print(s[-4:]) # Deck
print(s[::-1]) # reversed
This sample walks through methods in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: Methods
# Run in the REPL or save as a .py file and execute with python.
msg = " Hello, World "
print(msg.strip())
print(msg.lower().replace("world", "python"))
Here is a hands-on illustration of f-strings. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: f-strings
# Run in the REPL or save as a .py file and execute with python.
name, score = "Ada", 97.346
print(f"{name:<10} {score:7.2f}")
The program below demonstrates slice and stride. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Strings are immutable sequences — slices return new strings
word = "PythonDeck" # sample text
print(word[0], word[-1]) # first and last characters
print(word[2:8]) # slice from index 2 up to 8 (exclusive)
print(word[::2]) # every second character
print(word[::-1]) # reversed copy
escaped = "line1\nline2\t tab" # escape sequences
print(escaped) # shows newline and tab
raw = r"C:\new\file.txt" # raw string: backslashes literal
print(raw) # Windows path without \n escape
joined = "-".join(["a", "b", "c"]) # delimiter join
print(joined) # a-b-c
This sample walks through split and strip in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Text cleanup before parsing CSV-like input
line = " ada, 42 , active \n" # messy user input
clean = line.strip() # remove surrounding whitespace/newlines
print(repr(clean)) # show exact characters left
parts = [p.strip() for p in clean.split(",")] # trim each field
name, age, status = parts # unpack three fields
print(name, int(age), status.upper()) # normalize case
sentence = "the quick brown fox" # tokenize words
words = sentence.split() # default splits on any whitespace
print(len(words), words[0], words[-1]) # count, first, last
blob = "aaa" # repeat operator
print(blob * 3) # aaa aaa aaa without loop
Continue with these focused follow-up lessons on Python Strings: