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.
| Parameter | Description |
|---|---|
template | The pattern string containing placeholders. |
mapping | A 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.
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