20250423

Template strings

Official Documentation on Template Strings

A primary use case for template strings is for internationalization (i18n) since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python.

I have no experience with in

# This is copied from the official documentation mentioned above
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
d = dict(who='tim')
Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
Template('$who likes $what').safe_substitute(d)
'tim likes $what'

What I was surprised of first was the dict initialization. On second thought, the usage was obvious, but as I usually use d = {"who": "tim"}, the usage looked new to me.

In [1]: d1 = {"who": "tim"}

In [2]: d2 = dict(who="tim")

In [3]: d1 == d2
Out[3]: True

Trying the feature

In [1]: from string import Template

In [2]: template = Template("Kaz likes $favorite1, $favorite2, and $favorite3")

In [3]: kaz_favs_eng = {"favorite1": "apples", "favorite2": "berries", "favorite3": "banana"}

In [4]: template.substitute(kaz_favs_eng)
Out[4]: 'Kaz likes apples, berries, and banana'

In [5]: kaz_favs_jap = {"favorite1": "林檎", "favorite2": "ベリー", "favorite3": "バナナ"}

In [6]: template.substitute(kaz_favs_jap)
Out[6]: 'Kaz likes 林檎, ベリー, and バナナ'

TODO:


index 20250422 20250424