Fairly often I use the string.format()
for insertion of key-value pairs into a string template. The new Pep 498 f-strings have been recommended for a while but they seem to be a terrible choice for this behavior.
For instance if I wish to create a new f_string I need to make the variable first:
>>> date = 22
>>> date2 = f'this is a {date}'
>>> date2
'this is a 22'
Now if I try and perform the same action by creating an f-string
template but without having the replacement value initialized I get the expected NameError
>>> date_template = f'this is a new {date_new}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'date_new' is not defined
As there is no way to convert a string to f-string and f-strings
appear to be mainly syntatic sugar. Is there a non-obvious way of using f-strings
as templates or should I continue using string.format()
and string.format_map()
?