PEP498 - Literal String Interpolation

I hate myself for not knowing that this PEP has existing for Python 3.6.
While checking out task processing frameworks (mainly dramatiq), I found an example using f-strings and my mouth dropped to the floor.

Previously I was doing a lot of my string formatting using the **locals() trick, which is considered a bad practice.
This trick allows me to auto-format a format string with local variables without too much hassle.

(name, value,) = ('favorite number', 37,)
print('{name} is {value}'.format(**locals()))
# favorite number is 37

This worked fine for basic quick variable substitution, but was inefficient, featureless, and most importantly not-elegant.
Because I'm passing so many different variables (however are locally defined) to the format method, there is the feeling that a lot of unneeded effort is put on the back of Python's runtime.
Mainly, that feeling is the reason why f-strings were introduced to Python 3.61.

This new feature allows you to essentially do the following:

(name, value,) = ('favorite number', 37,)
print(f'{name} is {value}')
# favorite number is 37

And not only can you do this, but you can also use several format specifiers to quickly convert variables using builtin methods!
These are the current allowed sepcifiers:

Specifier Effect
variable!s str(varaible)
varaible!r repr(variable)
variable!a ascii(varaible

There are so many ridiculously useful features of this PEP that now I'm spending my days replacing many of my str.format instances with uses of f-strings.
This link has been really helpful in that process.

Some of these features include:

  • Math evaluation
  • Date formatting
  • Function calls

So basically, if your using Python 3.6 exclusively for a project, I would recommend trying out f-strings rather than using the default str.format.
It's so much more elegant.

1: Briefer string format:

You'll only receive email when Stephen Bunn publishes a new post

More from Stephen Bunn: