Introduction

Historically, formatting a string in Python, involved the % operator :

>>> qty, item, price = 12, "mugs", 15.3
>>> "The cost for %d %s is $%.2f" % (qty, item, qty * price)
'The cost for 12 mugs is $183.60'

Then, python introduced the format method to the str object and one could use :

>>> qty, item, price = 12, "mugs", 15.3
>>> "The cost for {:d} {:s} is ${:.2f}".format(qty, item, qty * price)
'The cost for 12 mugs is $183.60'

Which, you will convey, is still a bit cumbersome

f-strings, introduced with Python 3.6, provides a third way.

How it works

with f-strings, you use curly brackets to inject an expression into a strings that expression will be interpolated. The expression can be anything and formatted the same as with the format method :

>>> qty, item, price = 12, "mugs", 15.3
>>> f"The cost for {qty} {item} is ${qty * price:.2f}"
'The cost for 12 mugs is $183.60'

Noticed the f prefix ? - this is how you tell Python you are using an f-string and here is what happens if you forget it :

>>> qty, item, price = 12, "mugs", 15.3
>>> "The cost for {qty} {item} is ${qty * price:.2f}"
'The cost for {qty} {item} is ${qty * price:.2f}'

make sense ?

here is another quick example :

>>> bill = {'qty' : 12, 'item' : 'mugs', 'price' : 15.3}
>>> f"The cost for {bill['qty']} {bill['item']} is ${bill['qty'] * bill['price']:.2f}"
'The cost for 12 mugs is $183.60'

Conclusion

You can only use f-strings on Python 3.6 or higher. Today, we have all transitioned to Python 3, but a lot of systems are still running outdated versions of Python 3. I recently decommissioned our last VM under Squeeze, but still have tons of them running stock Whezzy and we are not yet ready for Stretch.

year version name python 2 python 3
2011 Debian 6 Squeeze 2.6 (default) 3.1
2013 Debian 7 Whezzy 2.7 (default) 3.2
2015 Debian 8 Jessie 2.7 (default) 3.4
2017 Debian 9 Stretch python 2.7 (default) 3.5

But this shouldn't stop you from using new Python features. Virtual environments are now easily deployed, docker can also help shipping applications with the exact language version the application was developed and tested.

If you can, start using f-strings right now !


Published

Category

Code

Tags

Contact