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

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.


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