string.templatelib — Support for template string literals
(docs.python.org)
Tipsad 2026-05-17 på Anders Ytterströms webblogg
Pythons stdlib har numera template strings
Python fick f-strings förra decenniet med 3.6, och fick en evolution på dessa i 3.14.
Template strings are a mechanism for custom string processing. They have the full flexibility of Python’s f-strings, but return a Template instance that gives access to the static and interpolated (in curly brackets) parts of a string before they are combined.
Otroligt användbart.
Templates are stored as sequences of literal strings and dynamic interpolations. A values attribute holds the values of the interpolations:
>>> cheese = 'Camembert'
>>> template = t'Ah! We do have {cheese}.'
>>> template.strings
('Ah! We do have ', '.')
>>> template.interpolations
(Interpolation('Camembert', ...),)
>>> template.values
('Camembert',)