f-Strings are formatted strings. They make it easy to insert values into a string from variables or expressions.
Example:
item = "sandwich" price = 4.99 text = f"You ordered a {item} for {price}." print(text) OUTPUT: You ordered a sandwich for 4.99.
Things to notice:
- Instead of just quotes, there is now an ‘f’ in front of the quotes.
- The variable names are inside {curly braces}.
If you did this using string concatenation, it would look like this:
text = "You ordered a " + item + " for "+ str(price) + "."
That’s more work, and it’s less readable than using f-Strings. Notice that it was also necessary to use the str() function to convert the number (price) to a string to avoid an error from trying to add a string to an integer. That conversion is not needed with f strings.
Math / Functions
You can put expressions inside the curly braces to get fancier.
Example:
qty = 4 price = 1.97 item = "soda" t = f"{qty} {item} x ${price} each = ${qty*price}" print(t) OUTPUT: 4 soda x $1.97 each = $7.88
In that example, two values are multiplied inside the f-String braces.
Any Python expression is allowed inside the braces, including functions.
Formatting Options
If you want to round numbers to two decimals, you can add :2f
inside the curly braces:
pi = 3.14159265358979323846 print(f"pi is approximately {pi:.2f}")
To print a percentage to one decimal place, add :1%
as follows:
fraction = 5/7 print(f"Percentage is {fraction:.1%}")
There are many other formatting options (thousand separators, padding, and more). Here’s a link that explains some of these:
https://www.pythonmorsels.com/string-formatting/
Older Python Versions
f-Strings were introduced in Python 3.6. If you’re in an older version, you can use str.format() instead.
Example:
item = 'fries' cost = '2.50' text = "The {} cost {}.".format(item, cost) print(text) OUTPUT: The fries cost 2.50.
In this version, you still use curly braces, but now they are empty. The .format() method’s parentheses needs to include the values, which will fill the curly braces in the order you listed them.