string.Template
Three rules: $identifier and ${identifier} are placeholders, $$ is a $, and any other $ is an error. That small surface is the point — a template written by a user or translator can only fill in names you provide.
Demo
from string import Template Template('Dear $name, your $item has shipped.').substitute(name='Ada', item='book')
A placeholder name is the longest run of ASCII letters, digits and underscores after the $, so '$items' asks for items, which is missing (KeyError) — '${item}s' is the fix. A $ followed by a space raises "Invalid placeholder in string: line 1, col 10" in the bare-$ case: the line and column (counted from 1) of that $. In '$naïve' the name stops before ï, so only na is looked up.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| template | str | yes | The template text. Stored unchanged as the instance attribute .template. |
Return value
Template — A template object. The text is kept in its .template attribute; nothing is parsed until you substitute.
Common patterns
from string import Template with open('welcome.txt', encoding='utf-8') as f: tpl = Template(f.read()) message = tpl.safe_substitute(name=user.name, plan=user.plan)
from string import Template Template('$host:$port').substitute(config, port=8080)
from string import Template tpl = Template(user_text) if not tpl.is_valid(): raise ValueError('stray $ in template') unknown = set(tpl.get_identifiers()) - {'name', 'plan'}
Examples
Pitfalls
from string import Template Template('$nounification').substitute(noun='simpl')
from string import Template Template('${noun}ification').substitute(noun='simpl')
from string import Template Template('Cost: $5').substitute()
from string import Template Template('Cost: $$5').substitute()
from string import Template Template('$user.name').substitute(user='ada')
from string import Template user = {'name': 'Ada'} Template('$user_name').substitute(user_name=user['name'])
When to use
- Message templates edited by users, admins or translators
- Config files with ${VAR}-style placeholders
- Any template whose author you do not fully trust
- Formatting numbers, dates, alignment → f-strings / str.format (Template has no format specs)
- Loops, conditionals, HTML → a template engine (Jinja2)
Notes
FAQ
f-strings are for code you write: they are evaluated where they appear. Template is for text that arrives at runtime — config, translations, user settings. It only replaces $names with the values you pass, so it cannot run code or read attributes.