Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a tool to automatically convert string formatting types to f-strings? [closed]

Tags:

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?

like image 807
mari.mts Avatar asked Jul 03 '19 19:07

mari.mts


People also ask

How do I change strings to f-string?

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.

Does F-string convert to string?

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.

Is F-string faster than format?

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.

What is f {} in Python?

“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.


1 Answers

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.

like image 90
ikamen Avatar answered Oct 11 '22 00:10

ikamen