On 23. December 2016 new minor version of Python was released – 3.6. It brings few enhancements and syntax features. In my opinion the most notable one is introduction of formatted string literals.

I always envied Ruby’s string interpolation because it is much cleaner and doesn’t require programmer to read end of expression just to understand what is substituted where.

String interpolation was always a pain in Python. Not to mention there is more than one way to do it…

Clear violation of Zen of Python that states:

There should be one– and preferably only one –obvious way to do it.

In order to violate it even more πŸ‘Ώ we have now third way to do the same thing. Yay!

Credit goes to xkcd

…but its actually better than previous ones. Syntax of first one is quite concise, but can cause some troubles for python newcomers:

There is a shortcut that allows to omit giving tuple as argument for string interpolation, but it won’t work with more than one argument. Nevertheless – this syntax makes it easy to format arguments just like old good sprintf does.

The same thing can be accomplished using “old-new” .format:

Way more verbose than previous syntax. Differences between string interpolation are presented on pyformat.info – awesome work done by Ulrich Petri and Horst Gutmann.

Getting back to new syntax – it naturally has all features of “old-new” string interpolation with .format function, but removes need to actually call this method.

This becomes especially helpful when formatting long strings (try to fit in standard PEP8’s 80 characters per line without awkward line breaks) or in classes:

This was merely a sneak peek of string formatting in Python, but it presented essential aspects of new so-called ‘f-strings’.