string — Template and constants

string.Template.substitute and safe_substitute, including KeyError and ValueError, plus capwords and punctuation, checked on Python 3.13.12. safe_substitute is not a security sanitizer.

モジュールページの本文は現在英語です。

The string module holds constants such as ascii_letters and punctuation, helpers such as capwords, and the Template class for $-substitutions. It is a standard-library module, not the built-in str type documented on the built-ins page.

Template.substitute() replaces $identifier and ${identifier} placeholders. A missing placeholder raises KeyError. A lone $ or another invalid placeholder raises ValueError. safe_substitute() leaves unrecognized or missing placeholders in the result instead of raising, which is useful for incomplete mappings. Official documentation describes that behavior as a safer substitution when some keys are absent; it is not an HTML, SQL, or shell sanitizer, and it does not escape values.

Examples were run against Python 3.13.12. They do not write files and they do not execute the interpolated strings.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Template.substitute errors

A Template is created from a pattern string. substitute() takes a mapping, keyword arguments, or both. Valid placeholders are $name and ${name} by default. $$ is an escaped dollar sign.

If a placeholder has no corresponding key, substitute() raises KeyError. If the pattern contains an invalid placeholder, such as a trailing $ with no name, it raises ValueError. Those exceptions are about placeholder syntax and missing keys, not about whether a value is safe to embed in HTML or SQL.

Template.substitute, KeyError, and ValueError

string.Template(template)
Template.substitute(mapping={}, /, **kws)

substitute() fills $name and ${name}. Missing keys raise KeyError. Invalid placeholders raise ValueError.

ParameterDescription
templateThe pattern string containing placeholders.
mappingA mapping of placeholder names to values. Keyword arguments can supply or override keys.

Returns: A new str with placeholders replaced by str(value).

Raises

  • KeyError — A valid placeholder has no value in the mapping or keyword arguments.
  • ValueError — The template contains an invalid placeholder, such as a trailing $.
  • The path in the successful substitution is a literal string, not a file that this example reads.
python
from string import Template

template = Template('Hello, $name. Path=${path}.')
print(template.substitute(name='Ada', path='/tmp/demo'))
try:
    template.substitute(name='Ada')
except KeyError as exc:
    print(type(exc).__name__, exc)
try:
    Template('bad $').substitute(name='Ada')
except ValueError as exc:
    print(type(exc).__name__, exc)

Expected output

Hello, Ada. Path=/tmp/demo.
KeyError 'path'
ValueError Invalid placeholder in string: line 1, col 5

Related: str methods, safe_substitute

Official documentation →

safe_substitute is not a sanitizer

safe_substitute() uses the same placeholder syntax, but missing or invalid placeholders are left in the output instead of raising. That makes it tolerant of partial mappings. It does not escape, quote, or otherwise neutralize the values it does insert.

If a value contains markup, SQL, or shell metacharacters, those characters remain in the result. Do not treat safe_substitute as a security filter. capwords() and the punctuation constant are ordinary string helpers and are also not sanitizers.

safe_substitute, capwords, and punctuation

Template.safe_substitute(mapping={}, /, **kws)
string.capwords(s, sep=None)
string.punctuation

safe_substitute() leaves missing placeholders unchanged and inserts values as-is. It is not a sanitizer.

ParameterDescription
mapping, kwsThe same mapping and keyword arguments as substitute(). Missing keys are not an error.
s, sepcapwords() splits, capitalizes each word, and joins. If sep is omitted, whitespace is collapsed.

Returns: safe_substitute() and capwords() return a str. punctuation is a str constant of ASCII punctuation characters.

  • The second print inserts a markup string unchanged. Nothing is rendered or executed here.
python
from string import Template, capwords, punctuation

template = Template('Hello, $name. Path=${path}.')
print(template.safe_substitute(name='Ada'))
print(Template('Hello, $name').safe_substitute(name='<script>alert(1)</script>'))
print(capwords('hello from python'))
print(punctuation)

Expected output

Hello, Ada. Path=${path}.
Hello, <script>alert(1)</script>
Hello From Python
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Related: Template.substitute, html.escape is also not a general sanitizer

Official documentation →