🐍 Python
String Interpolation

Updated at 2018-06-11 02:01

Avoid "old style" % string formatting.

name: str = 'John'
assert ('Hello, %s!' % name) == 'Hello, John!'

Avoid "new style" .format string formatting. But the "new style" is better than the "old style" formatting.

name: str = 'John'
assert 'Hello, {}!'.format(name) == 'Hello, John!'

Use formatted string literals f'' String literals are more efficient, and are like JavaScript template literals. Available in Python 3.6+

name: str = 'John'
assert f'Hello {name}!' == 'Hello John!'

Use template strings if receiving the template from an untrusted source.

from string import Template

name: str = 'John'
t: Template = Template('Hello, $name!')
assert t.substitute(name=name) == 'Hello, John!'