The Zen of Python asserts there should be "one obvious way to do something in Python". But when it comes to string formatting, things are a little .... less zen. It can be surprising to find out that there are four main ways to perform string formatting in Python - each for a different scenario. Some of this is due to Python's long history and some of it is due to considerations like internationalization or input sanitation.
With 4 different paths to take, how do you decide what to use?
f-stringsare the newest and easiest to read. If you don't need to internationalize, they should be the Python 3.6+ preferred method.str.format()is versatile, very powerful and compatible with bothgnu gettextand most versions of Python.- If simplicity, safety, and/or heavy internationalization is what you need,
string.Template()can be used to mitigate risks when inputs need to be handled and for wrapping translation strings. - The
%operator should mostly be used for compatibility with old code.%formatting` can lead to issues displaying non-ascii and unicode characters and has more errors and less functionality than other methods.
If you want to go further: all about formatting and Python String Formatting Best Practices are good places to start.