consider-using-f-string / C0209¶
Message emitted:
Formatting a regular string which could be an f-string
Description:
Used when we detect a string that is being formatted with format() or % which could potentially be an f-string. The use of f-strings is preferred. Requires Python 3.6 and ``py-version >= 3.6``.
Problematic code:
from string import Template
menu = ("eggs", "spam", 42.4)
old_order = "%s and %s: %.2f ¤" % menu # [consider-using-f-string]
beginner_order = menu[0] + " and " + menu[1] + ": " + str(menu[2]) + " ¤"
joined_order = " and ".join(menu[:2])
# +1: [consider-using-f-string]
format_order = "{} and {}: {:0.2f} ¤".format(menu[0], menu[1], menu[2])
# +1: [consider-using-f-string]
named_format_order = "{eggs} and {spam}: {price:0.2f} ¤".format(
eggs=menu[0], spam=menu[1], price=menu[2]
)
template_order = Template("$eggs and $spam: $price ¤").substitute(
eggs=menu[0], spam=menu[1], price=menu[2]
)
Correct code:
menu = ("eggs", "spam", 42.4)
f_string_order = f"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤"
Additional details:
Formatted string literals (f-strings) give a concise, consistent syntax
that can replace most use cases for the %
formatting operator,
str.format()
and string.Template
.
F-strings also perform better than alternatives; see this tweet for a simple example.
Created by the refactoring checker.