← retour aux snippets

string.Template: templating simple et safe_substitute

Remplacer des variables dans un gabarit sans lever d'exception.

python templating #string

objectif

Remplacer des variables dans un gabarit sans lever d’exception.

code minimal

from string import Template
t = Template("Hello $name, id=$id")
out = t.safe_substitute(name="Ada")
print("Hello Ada, id=" in out)  # attendu: True

utilisation

from string import Template
tpl = Template("Path: $root/$file.txt")
s = tpl.substitute(root="/tmp", file="x")
print(s.endswith("/tmp/x.txt"))

variante(s) utile(s)

from string import Template
print(isinstance(Template("$x"), Template))

notes

  • substitute lève KeyError si une variable manque; safe_substitute non.
  • Évitez pour des besoins complexes, préférez un moteur dédié.