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.
In [1]:
stuff = {
'apple': 1.97,
'banana': 2.99,
'cherry': 3.99,
}
In [2]:
# Common pattern of .format use:
for name, price in stuff.items():
print(
'The price of {name} is {price}'.
format(name=name, price=price))
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.
In [3]:
for name, price in stuff.items():
print(f'The price of {name} is {price}')
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.
In [4]:
tax = 0.50
for name, price in stuff.items():
print(f'The total price of {name} is {round(price * (1+tax), 2)}')
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.
In [5]:
template = lambda: f'tes{k}'
template
Out[5]:
In [6]:
k = 9
template()
Out[6]:
In [7]:
k = 8
template()
Out[7]:
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.
In [8]:
def template():
return f'tes{k}'
In [9]:
k = 9
template()
Out[9]:
In [10]:
k = 8
template()
Out[10]: