Learn by reading through in order

string and textwrap — Character Constants, Templates, and Formatting

Use string.ascii_letters / digits and string.Template's $name substitution, plus textwrap.dedent for indent removal and fill for width wrapping on an order email.

What string and textwrap are for

string and textwrap are helper modules that complement everyday string handling. string provides character constants (collections of letters, digits, and symbols) and Template ($name-style template substitution); textwrap handles multi-line string formatting (indent removal and width wrapping). You'll reach for them when f-strings or replace aren't enough.

When to use string vs textwrap
string moduleconstants + Templateletter / digit checksemail body templatestextwrap modulededent + fillindent removalwidth wrappinguse casesuse cases
string shines at character sets and template substitution, while textwrap is for cleaning up the look of multi-line strings. Both are standard library modules, and since their use cases don't overlap, the easiest way to remember them is by role.

string — Character Constants and Template Substitution

The string module has two kinds of features. The first is character constants like string.ascii_letters (52 letters), string.digits (09), and string.punctuation (symbols), which save you from defining "what counts as a letter / digit" yourself.

The second is string.Template — you embed $name-style $-prefixed variables in a string and later replace them with substitute(name="value"). It looks similar to f-strings (f"{name}"), but Template has a simple, safe parser, which makes it a good fit when the template itself comes from user input (such as email body templates).

What string offers
constantsascii_letters / digits"letters only?"checks / generationTemplate$name-style templatesubstitute(name=value)replacement
Character constants are used to check or generate "letters / digits / symbols". Template is a lightweight, safe template engine that replaces $name-style placeholders in a string with values via substitute.
Constant / ClassContentsUse
string.ascii_lowercaseabcdefghijklmnopqrstuvwxyz26 lowercase letters
string.ascii_uppercaseABCDEFGHIJKLMNOPQRSTUVWXYZ26 uppercase letters
string.ascii_lettersthe two above joined (52 chars)letter checks, random string generation
string.digits0123456789digit checks
string.punctuation! " # $ % & ' ... etcsymbol checks
string.Template(s)$name-style template classemail bodies, notification templates

Build an order confirmation email template with string.Template, then drop in a customer name and order number.

① Import the string module.

② Print the total length of the letter constant in the form Letters: ◯ (you'll get 52 — uppercase + lowercase).

③ Print the contents of the digits constant in the form Digits: ◯◯.

④ Build a Template object from the template string "Hello, $name! Order #$order_id is ready.".

⑤ Print the result of substituting name="Alice" and order_id=1234.

(If you run this correctly, an explanation will appear.)

Python Editor

Run code to see output

textwrap — Stripping Triple-Quote Indents and Wrapping Width

textwrap is a standard library module for prettifying strings. The two functions you'll use most are textwrap.dedent (which strips the common leading indent from text written in triple-quoted form) and textwrap.fill (which wraps a long string to a given width).

When you write multi-line strings like """...""" in code, your source-level indent ends up baked into the string itself. dedent removes only the common leading whitespace, so your code stays nicely indented while the string itself comes out clean.

How textwrap.dedent works
string in source Hello Sunny todaytextwrap.dedentcleaned stringHelloSunny today
Strips the common leading indent baked into a triple-quoted string, leaving the code structure intact while cleaning up the string itself. It auto-detects the number of leading spaces shared by every line and removes that much.
FunctionWhat it doesReturns
textwrap.dedent(text)remove the common leading indentthe cleaned string
textwrap.fill(text, width=N)wrap to width N as one stringsingle string with newlines
textwrap.wrap(text, width=N)split into lines at width Nlist of strings
textwrap.shorten(text, w)if the result wouldn't fit width N, end with [...]the truncated string
import textwrap

# dedent: strip the indent from a triple-quoted string
raw = """
    Hello.
    What a nice day today.
    """
print(textwrap.dedent(raw).strip())
# Hello.
# What a nice day today.

# fill: wrapping (English shows it most clearly)
long_text = "Python is a language that lets you work quickly and integrate systems."
print(textwrap.fill(long_text, width=30))
# Python is a language that
# lets you work quickly and
# integrate systems.

Combine dedent with strip

Triple-quoted strings often start and end with a newline, so the one-liner textwrap.dedent(raw).strip() (dedent + trim surrounding whitespace) is a common pattern. strip is a built-in string method that removes whitespace (newlines included) from both ends.

Clean up an error-message template written with indentation using dedent, then wrap an English sentence with fill.

① Import textwrap.

② Define a 2-line English string indented by 4 spaces inside a triple-quoted string (with empty lines at the very start and end).

③ Strip the indent and the surrounding whitespace, then print --- after dedent --- before the formatted result.

④ Wrap the English sentence "Python is a language that lets you work quickly and integrate systems." to a width of 30 characters, and print --- after fill --- before the result.

Python Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1What is the result of string.Template("Hi $name").substitute(name="Bob")?

Q2Which one removes the common leading indent from text written in triple quotes (with source-level indentation)?

Q3What does textwrap.fill(text, width=20) do?