There is no difference, technically speaking. The f-string
format is recommended because it is more recent: it was introduced in Python 3.6. RealPython explains that f-strings
are faster than str.format()
.
With f-strings
the syntax is less verbose. Suppose you have the following variables:
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
This is how you would format a str.format()
statement.
print(("Hello, {name} {surname}. You are {age}. " +
"You are a {profession}. You were a member of {affiliation}.") \
.format(name=first_name, surname=last_name, age=age,\
profession=profession, affiliation=affiliation))
With formatting strings, it is considerably shortened:
print(f"Hello {first_name} {last_name}. You are {age}" +
f"You are a {profession}. You were a member of {affiliation}.")
Not only that: formatting strings offer a lot of nifty tricks, because they are evaluated at runtime:
>>> name="elvis" # note it is lowercase
>>> print(f"WOW THAT IS {name.upper()}")
'WOW THAT IS ELVIS'
This can be done inside a str.format(...)
statement too, but f-strings
make it cleaner and less cumbersome. Plus, you can also specify formatting inside the curly braces:
>>> value=123
>>> print(f"{value=}")
'value = 123'
Which normally you should have written as print("value = {number}".format(number=value))
. Also, you can evaluate expressions:
>>> print(f"{value % 2 =}")
'value % 2 = 1`
And also format numbers:
>>> other_value = 123.456
>>> print(f"{other_value:.2f}") # will just print up to the second digit
'123.45'
And dates:
>>> from datetime.datetime import now
>>> print(f"{now=:%Y-%m-%d}")
'now=2022-02-02'