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 tool doing this. Is there a tool to automatically convert literals using old string formatting to f-strings?
Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os. linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.
An f-string is syntax, not an object type. You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.
f-strings are faster than both %-formatting and str. format() . At runtime, each expression inside the curly braces gets evaluated within its own scope, and then it's put together into the final string.
“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f , which contains expressions inside braces.
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:
https://medium.com/@ikamen/f-strings-make-your-python-code-faster-and-more-readable-today-579ef9ca0313
Disclaimer: I am the author of flynt package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With