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

Question:

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?

Asked By: mari.mts

||

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.

Answered By: ikamen

It looks like pyupgrade is capable of both converting % formatting to format calls, and format calls to f-strings

printf-style string formatting

Availability:

Unless --keep-percent-format is passed.

'%s %s' % (a, b)                  # '{} {}'.format(a, b)
'%r %2f' % (a, b)                 # '{!r} {:2f}'.format(a, b)
'%(a)s %(b)s' % {'a': 1, 'b': 2}  # '{a} {b}'.format(a=1, b=2)

f-strings

Availability:

--py36-plus is passed on the commandline.

'{foo} {bar}'.format(foo=foo, bar=bar)  # f'{foo} {bar}'
'{} {}'.format(foo, bar)                # f'{foo} {bar}'
'{} {}'.format(foo.bar, baz.womp}       # f'{foo.bar} {baz.womp}'

note: pyupgrade is intentionally timid and will not create an f-string if it would make the expression longer or if the substitution parameters are anything but simple names or dotted names (as this can decrease readability).

Answered By: Francisco
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.