DEV Community

Cover image for Python: What is an f-string?
Adam Lombard
Adam Lombard

Posted on • Updated on

Python: What is an f-string?

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}"
Enter fullscreen mode Exit fullscreen mode

Say, for instance, we want to print a user greeting where the username is variable:

username = 'Ellen'
print(f"Hello, {username}!")
Enter fullscreen mode Exit fullscreen mode
Hello, Ellen!
Enter fullscreen mode Exit fullscreen mode

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}.")
Enter fullscreen mode Exit fullscreen mode
The year is 2020. A decade from now, the year will be 2030.
Enter fullscreen mode Exit fullscreen mode

F-strings were added in Python 3.6.


Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


Top comments (12)

Collapse
 
waylonwalker profile image
Waylon Walker

Any version of python before 3.6 was dead to me the instant f-strings came out. They are so freaking useful!

Collapse
 
adamlombard profile image
Adam Lombard

Yes, they're very handy!

Collapse
 
muhimen123 profile image
Muhimen

f-string? Better way to use .format()

Keep in mind, f-string is only available for python 3.6 and upper

Collapse
 
adrianmarkperea profile image
Adrian Perea

I find the syntax of format a little bit harder to read than f-strings. F-strings make strings with variables read like prose

Collapse
 
adamlombard profile image
Adam Lombard

Thank you for noting the Python version. Excellent point!

Collapse
 
syntax753 profile image
Peter Turner • Edited

Shouldn't you edit the article to mention the version?
Good article in any case :)

Thread Thread
 
adamlombard profile image
Adam Lombard

Yes, thanks for the suggestion. :)

Collapse
 
sanyaldips93 profile image
Dipayan Sanyal

A nice shorthand of the format function.

A beautiful explanation. (Y)

Collapse
 
muhimen123 profile image
Muhimen

What is that (Y) doing at the end? 😅

Collapse
 
sanyaldips93 profile image
Dipayan Sanyal

I was trying to give a thumbs up

Thread Thread
 
eljayadobe profile image
Eljay-Adobe

(👍🏻)

Collapse
 
adamlombard profile image
Adam Lombard

Thank you!