f-strings are new in Python 3.6.
f-strings look like an ordinary strings with an f in front. They look like an ordinary (immutable) string that does not change, but they are not immutable strings.
One can put arbitrary expressions within curly braces in an f-string, and the arbitrary expressions will be evaluated each time, and then converted to a string. The most common expressions used are just variable names.
It is a more DRY way of doing formatting than str.format.
First let's look at how format is often done with the str.format method.
stuff = {
'apple': 1.97,
'banana': 2.99,
'cherry': 3.99,
}
# Common pattern of .format use:
for name, price in stuff.items():
print(
'The price of {name} is {price}'.
format(name=name, price=price))
The price of apple is 1.97 The price of banana is 2.99 The price of cherry is 3.99
Something that sucks about the above print, is that name and price appear three times each. I.e., It is not DRY.
With f-strings, name and price only have to appear once, making the code easier to read and maintain as in the following example.
for name, price in stuff.items():
print(f'The price of {name} is {price}')
The price of apple is 1.97 The price of banana is 2.99 The price of cherry is 3.99
It reminds me of shell syntax. For example,
echo "The price of ${name} is ${price}"
It gets better. One may put arbitrary expressions within the curly braces in an f-string. One is not limited to using just variable names.
tax = 0.50
for name, price in stuff.items():
print(f'The total price of {name} is {round(price * (1+tax), 2)}')
The total price of apple is 2.96 The total price of banana is 4.49 The total price of cherry is 5.99
Then some crazy whacko guy named zak showed a crazy whacko lambda with no arguments that had an f-string for the body.
This makes my head wobble. I am wondering what good uses (if any) there are for this.
template = lambda: f'tes{k}'
template
<function __main__.<lambda>>
k = 9
template()
'tes9'
k = 8
template()
'tes8'
2017-02-25 afterthought:
Since it is saved in a variable, the lambda above is a poor use of a lambda. It would be better to just make it a regular (named) function as shown below.
I still do not know what good uses (if any) there are for the f-string below.
def template():
return f'tes{k}'
k = 9
template()
'tes9'
k = 8
template()
'tes8'