Since Python 3.6, a new feature called formatted string literals or f-strings has been introduced to the string fomatting arsenal. It boasts better simplicity and readability than the reigning strategy, str.format
.
Demo
Here is a simple example of f-strings:
from datetime import datetime
name = 'Jiaxi'
start = datetime(2018, 10, 29)
f'Hello {name}, you have spent {(datetime.now() - start).days} days at Alibaba!'
>>>
In comparison, the old str.format
is less readable.
'Hello, {}! you have spent {} days at Alibaba!'.format(
name, (datetime.now() - start).days
)
There is another way to format strings, called template strings, that could come handy in niche situations.
from string import Template
t = Template('Hello, $name! you have spent $days days at Alibaba!')
t.substitute(name=name, days=(datetime.now() - start).days)
This method works well ingesting user-generated tokens and strings, preventing security issues.