Skip to content

printf-string-formatting (UP031)#

Derived from the pyupgrade linter.

Fix is sometimes available.

What it does#

Checks for printf-style string formatting.

Why is this bad?#

printf-style string formatting has a number of quirks, and leads to less readable code than using str.format calls or f-strings. In general, prefer the newer str.format and f-strings constructs over printf-style string formatting.

Known problems#

This rule is unable to detect cases in which the format string contains a single, generic format specifier (e.g. %s), and the right-hand side is an ambiguous expression.

For example, given:

"%s" % value

value could be a single-element tuple, or it could be a single value. Both of these would resolve to the same formatted string when using printf-style formatting, but not when using f-strings:

value = 1
print("%s" % value)  # "1"
print("{}".format(value))  # "1"

value = (1,)
print("%s" % value)  # "1"
print("{}".format(value))  # "(1,)"


"%s, %s" % ("Hello", "World")  # "Hello, World"

Use instead:

"{}, {}".format("Hello", "World")  # "Hello, World"