string
Not where the string methods live — those are on str itself. The string module adds ASCII character sets, capwords(), the $name Template for user-editable text, and Formatter, which lets you subclass str.format.
import string from string import Template, Formatter, capwords
Demo
from string import Template Template('$who likes $what').substitute(who='Ada', what='tea')
capwords splits on whitespace, so it only capitalizes the first letter of each space-separated word and collapses runs of spaces; title() starts a new word after every non-letter, giving "They'Re". Template raises KeyError('whom') for an unknown name and "Invalid placeholder in string: line 1, col 10" for the $ before 10 (the column of that $, counted from 1). string.punctuation is ASCII only: curly quotes, the dash and the ellipsis survive the filter.
Members
Common patterns
from string import Template msg = Template(settings["welcome"]).safe_substitute(name=user.name)
import secrets, string alphabet = string.ascii_letters + string.digits password = "".join(secrets.choice(alphabet) for _ in range(16))
import string clean = text.translate(str.maketrans("", "", string.punctuation))
import string class Lenient(string.Formatter): def get_value(self, key, args, kwargs): if isinstance(key, str): return kwargs.get(key, "{" + key + "}") return super().get_value(key, args, kwargs) Lenient().format("{a} {b}", a=1)
Examples
Pitfalls
import string string.join(['a', 'b'], '-')
'-'.join(['a', 'b'])
import string string = 'abc' string.digits
import string text = 'abc' string.digits
import string 'é' in string.ascii_letters
'é'.isalpha()
When to use
- Character sets for validation, filtering and password generation (ASCII)
- Templates whose text is written by users or translators — Template
- Changing how {fields} are looked up or formatted — subclass Formatter
- Everyday formatting → f-strings or str.format
- Unicode-aware character tests → str.isalpha, isdigit, isspace
- HTML or large templates → a template engine (Jinja2, string.Template is deliberately minimal)
Notes
FAQ
Nine str constants (ascii_letters, ascii_lowercase, ascii_uppercase, digits, hexdigits, octdigits, punctuation, printable, whitespace), the function capwords, and two classes: Template for $-placeholder substitution and Formatter, an overridable version of str.format. The usual string methods (upper, split, replace …) are on str, not in this module.