Skip to content

Replace Interpolation With Fstring

Sourcery refactoring id: replace-interpolation-with-fstring

Description

Replace usage of string interpolation % operator with f-strings

Before

print("Good %s, %s %s" % (time_of_day, first_name, last_name))

After

print(f"Good {time_of_day}, {first_name} {last_name}")

Explanation

The Python documenation notes that using the % operator to format strings can lead to 'a variety of quirks that lead to a number of common errors'.

Python added f-strings in version 3.6, with PEP 498. F-strings are a flexible and powerful way to format strings. They make the code shorter and more readable, since the code now looks more like the output.

Note that for the moment this refactoring only supports replacement of formatting that uses the %s operator.

Back to top