In Python, f-strings are a string formatting mechanism that allow us to embed Python expressions in string literals. 'F-string' is short for 'formatted string'.
They are formatted like so:
f"string literal {expression}"
Say, for instance, we want to print a user greeting where the username is variable:
username = 'Ellen'
print(f"Hello, {username}!")
Hello, Ellen!
Any valid Python expression can be used in the f-string brackets:
year = 2020
print(f"The year is {year}. A decade from now, the year will be {year + 10}.")
The year is 2020. A decade from now, the year will be 2030.
F-strings were added in Python 3.6.
Was this helpful? Did I save you some time?
Top comments (12)
Any version of python before 3.6 was dead to me the instant f-strings came out. They are so freaking useful!
Yes, they're very handy!
f-string? Better way to use .format()
Keep in mind, f-string is only available for python 3.6 and upper
I find the syntax of format a little bit harder to read than f-strings. F-strings make strings with variables read like prose
Thank you for noting the Python version. Excellent point!
Shouldn't you edit the article to mention the version?
Good article in any case :)
Yes, thanks for the suggestion. :)
A nice shorthand of the format function.
A beautiful explanation. (Y)
What is that
(Y)
doing at the end? πI was trying to give a thumbs up
(ππ»)
Thank you!