Using interpolated format strings in Python

The release of Python 3.6 came with exciting functionalities. I want to speak about the feature called interpolated format string – f-strings for short- through this quick post. This new feature allows us to have a more readable, concise and even faster way of formatting string, in short words: pythonic code.

One of the most interesting features associated with the f-string is the capacity to include expressions which can be solved. The Python syntax is:

As you can observe, it is simple compared to previous functions, and it is less prone to commit mistakes as can happen when you depend on the variables order such as string.format syntax. As I mentioned above, using F-strings also enables you to put a full Python expression within the
placeholder braces. See the following example:

It is interesting to remark on the capacity to include a format function inside of placeholder braces too. In this example, we formatted the length of the variable .. more explanation. By default, f-string use __str__(). Nonetheless, you could use __repr__() which can be helpful in case you want to get the parable string representation of an object; you only need to include the conversion flag !r as in this example:

As in the previous example, you are able to apply a format to variables parsed, including the number of digits after the decimal, justification on the string, etc. You can find more details about it here.

Finally, the following example shows you the speed of both approaches. We are using a library called timeit, its usage is simple and consists in supplying a statement of the number of iterations to be executed.

Once you execute, please observe the time delta between both options and you will have an additional reason to start using f-string over any older approach. Last but not least, thanks to my colleague and large landowner Esteban (SRE rockstar) at Languagewire for sharing this syntax. Happy coding!