On this page
  1. string
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe User-Supplied Templates (safe_substitute)
  7. 2. Building Character Allowlists
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

string

Prev: statistics | Up: stdlib_module | Next: stringprep
Rel: re, difflib, textwrap, unicodedata, stringprep
Ref: docs.python.org — string
Tags: #public #python3 #stdlib


Import

import string

Overview

ASCII character-class constants (ascii_letters, ascii_lowercase, digits, hexdigits, punctuation, whitespace), safe $variable template substitution (Template), and extensible Formatter. Reach for string.Template when user-supplied templates must not access arbitrary Python attributes (unlike str.format).

Quick Start

import string

assert "a" in string.ascii_lowercase and "9" in string.digits

tmpl = string.Template("Hello, $name! Your role is ${role}.")
assert tmpl.substitute(name="Ada", role="admin") == "Hello, Ada! Your role is admin."

Implementation Walkthrough

1. Safe User-Supplied Templates (safe_substitute)

Unlike str.format() (which allows attribute/item traversal on passed objects), string.Template only substitutes explicit $identifier placeholders—and safe_substitute() leaves unknown placeholders intact instead of raising KeyError:

from string import Template

tmpl = Template("Report for $user ($date) — $missing")
rendered = tmpl.safe_substitute(user="Ada", date="2026-12-01")
assert rendered == "Report for Ada (2026-12-01) — $missing"

2. Building Character Allowlists

import string

HEX_CHARS = frozenset(string.hexdigits)
assert all(ch in HEX_CHARS for ch in "deadBEEF42")

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes