So, Python 3.6 has better string formatting19 Apr 2016
Differently from Python 3.5, which introduced lots of new features to the language the 3.6 release is basically about enhancing performance, fixing bugs and deprecating stuff. Out of those modifications, the most important is the deprecation of
await as variable names, since they will become language keywords due to the new coroutines syntax as explained in PEP 492.
However, Python 3.6 presents the users one more way to format strings, defined in PEP 498. This feature is heavily inspired by string interpolation as implemented in other programming languages, such as Ruby, Perl, Shell Script, Scala, and Swift, and tries to do easier string formatting. But what’s wrong with our current methods?
First, the old
%-formatting supports only a limited number of types: integers, strings, and floats. Any other type must be casted to string to become valid. This casting presents a well-known problem when the only argument to be formatted is a tuple, since
%-formatting uses brackets in its own syntax.
Trying to solve some of these problems,
str.format() provided string formatting with usual method call syntax, as well as better support for custom types, as detailed in PEP 3101. However, this came with the cost of verbosity and boilerplate code, specially for simple scenarios that were supposed to as small and easy as a “hello, world!”.
In Python 3.6, we can now benefit com
f-strings and its string interpolation magics. For instance, the previous example would simply become the following. Note that the only requirement is to precede the string with an
In fact, it supports even more advanced tricks, such as accessing variable attributes directly, combining with raw strings to create regular expressions, for instance, and even parsing results from lambda expressions.
That’s it. What are your thoughts on
f-strings? Will you replace your preferred string formatting method by this one?