Since python 3.6, the shortest and most performant way to format values into a string are PEP 498 f-strings (e.g. f'Hello {name}'
).
Converting older formatting types ('Hello %s' % name
, 'Hello {}'.format(name)
) to the new one in an existing code base appears to be a task that could be automated, however I could not find any simple way to do this. Is there a simple method to automatically convert literals using old string formatting to f-strings in Python code? Maybe with an IDE or with regular expressions?
You can use flynt to convert multiple python files to use f-strings.
To run it, you need a python 3.6+ interpreter. Then, its as simple as:
pip install flynt
flynt [relative or absolute path to the root of your project]
Keep in mind that it will change files in place, so it is advisable to commit those to git or SVC system of your preference.
Here is an article describing the pros and cons of f-strings:
Disclaimer: I am the author of flynt package.