Saturday, 16 September 2023

Self documenting expressions in f-strings

A formatted string literal feature I didn't know about

tags: f-strings, python

What have I learnt?

There's a feature in f-strings that comes in quite useful when printing out variables. Consider the following example of printing variables

>>> weather = "sunny"
>>> temperature = 28
>>> rain_expected = False
>>> f"weather: {weather}, temperature: {temperature}, rain_expected: {rain_expected}"
'weather: sunny, temperature: 28, rain_expected: False'

It turns out you can just pop an = after the expression and it will expand to include the expression, an equals sign, and the result:

>>> f"{weather=}, {temperature=}, {rain_expected=}"
"weather='sunny', temperature=28, rain_expected=False"
>>> f"{math.pow(10,2)=}"
'math.pow(10,2)=100.0'

It will also take into account spaces in the expression:

>>> f"{2+2=}"
'2+2=4'
>>> f"{2 + 2 = }"
'2 + 2 = 4'