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.

TextPython 3 (all)Live demo
Import
import string
from string import Template, Formatter, capwords
Constants
ascii_letters, ascii_lowercase, ascii_uppercase, digits, hexdigits, octdigits, punctuation, printable, whitespace — all plain str, all ASCII
Function
capwords(s, sep=None) — split, capitalize each word, join
Classes
Template ($name placeholders, substitute / safe_substitute) and Formatter (str.format as overridable methods)
Not here
upper, split, strip, replace … are str methods; the old string.upper()-style functions were removed in Python 3

Demo

Live evaluation
Fill $placeholders. A missing name raises KeyError; a $ that is not a placeholder raises ValueError.
Try:
Inputs
textstrtemplate with $who and $what
whostrvalue for who
whatstrvalue for what
Code
from string import Template
Template('$who likes $what').substitute(who='Ada', what='tea')
Result
'Ada likes 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

Methods & attributes7
LIVE
Formatter.check_unused_args
check_unused_args(used_args, args, kwargs)
Hook called once at the end of vformat with the set of argument keys the format string actually used — override it to reject unused arguments.
LIVE
Formatter.convert_field / format_field
convert_field(value, conversion) · Formatter.format_field(value, format_spec)
The last two steps for every field: convert_field applies !r / !s / !a, then format_field applies the :spec by calling the built-in format().
LIVE
Formatter.get_value / get_field
get_value(key, args, kwargs) · Formatter.get_field(field_name, args, kwargs)
The lookup hooks of string.Formatter: get_field resolves a whole field name like "0[1].y", get_value fetches its first part from args or kwargs.
LIVE
Formatter.parse
parse(format_string)
Split a str.format-style string into (literal_text, field_name, format_spec, conversion) tuples — the way to find out which fields a format string uses.
LIVE
Template.delimiter / idpattern / braceidpattern / flags / pattern
class T(Template): delimiter = … · idpattern = … · braceidpattern = … · flags = … · pattern = …
The class attributes a Template subclass overrides to change the syntax: the $ itself, what counts as a name, the flags of the regex — or the whole regex.
LIVE
Template.get_identifiers / is_valid
get_identifiers() · Template.is_valid()
Inspect a Template without substituting: the placeholder names it uses, in first-seen order, and whether substitute() could run without a ValueError.
LIVE
Template.substitute / safe_substitute
substitute(mapping={}, /, **kwds) · Template.safe_substitute(mapping={}, /, **kwds)
Fill a Template: substitute raises KeyError for a missing name and ValueError for a stray $, safe_substitute leaves both in the text.

Common patterns

User-editable message templates
Template is safe for text written by non-programmers: no attribute access, no format specs, no code.
from string import Template
msg = Template(settings["welcome"]).safe_substitute(name=user.name)
Random password from character sets
Combine the constants and draw with the secrets module.
import secrets, string
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))
Strip ASCII punctuation
str.translate with a deletion table is the fast way.
import string
clean = text.translate(str.maketrans("", "", string.punctuation))
A Formatter that tolerates missing keys
Override get_value to supply a default.
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

1. Letters and digits
import string string.ascii_letters + string.digits
Returns
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
2. Membership test
import string all(c in string.hexdigits for c in 'C0FFEE')
Returns
True
3. capwords
import string string.capwords('hello world')
Returns
'Hello World'
4. Template substitution
from string import Template Template('$who likes $what').substitute(who='Ada', what='tea')
Returns
'Ada likes tea'
5. safe_substitute keeps unknowns
from string import Template Template('$who likes $what').safe_substitute(who='Ada')
Returns
'Ada likes $what'
6. Formatter works like str.format
import string string.Formatter().format('{0}-{x}', 'a', x='b')
Returns
'a-b'
7. The module has no upper()
import string string.upper('x')
Returns
AttributeError: module 'string' has no attribute 'upper'

Pitfalls

1. Calling Python 2 string functions
string.upper, string.split, string.join and friends were removed in Python 3. They are methods of str.
string.join
import string
string.join(['a', 'b'], '-')
AttributeError: module 'string' has no attribute 'join'
str.join
'-'.join(['a', 'b'])
'a-b'
2. Naming a variable string
A variable called string shadows the module, and the next string.digits fails.
shadowed
import string
string = 'abc'
string.digits
AttributeError: 'str' object has no attribute 'digits'
another name
import string
text = 'abc'
string.digits
'0123456789'
3. Treating the constants as Unicode-aware
Every constant is ASCII only. For any letter or digit use str.isalpha() / isdigit().
ascii_letters
import string
'é' in string.ascii_letters
False
str.isalpha
'é'.isalpha()
True

When to use

Use it
  • 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
Reach for something else
  • 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

CPython impl
Lib/string.py — pure Python; Formatter reuses the C parser behind str.format through _string.formatter_parser and _string.formatter_field_name_split
Constants
Fixed ASCII strings, not locale-dependent (the Python 2 string.letters/lowercase/uppercase that followed the locale are gone)
Template
Default placeholder pattern: $ followed by an ASCII identifier, or the same in braces; $$ is a literal $

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.