f-strings | String Formatting in Python

The string's formatting style makes a string more readable, more concise, and less prone to error. Python 3.6 or a newer version, f-strings are a great new way to format strings. Printing output in Python is facilitated with f-string as it can be considered WYSIWYG (What You See is What You Get). When you prefix the string with the letter 'F, the string becomes the f-string itself.

Within quotes

Strings enclosed within double quotes ("" ) or single quotes (''), you only need to add an f or an F before the opening quotes of your string. The letter 'f' also indicates that these strings are used for formatting.
print(F"This is f-string")
Output: This is f-string
Note: You can't use backslashes to escape in the expression part of an f-string.

Display variables

When display variables, you only need to specify the names of the variables inside a set of {} curly braces.
var = 'World' print(f"Hello, {var} !!!")
Output: Hello, World !!!

Evaluate Expressions

When you want to evaluate expression, you need to insert the expression inside a set of curly braces {}.
x = 5 y = 4 print(f"Result is {x * y}.")
Output: Result is 20

Using in Dictionary

You can use dictionary keys inside the f-string.
myDict = {"brand": "Ford", "model": "Mustang"} print(f"My car is {myDict['brand']}-{myDict['model']}.")
Output: My car is Ford-Mustang.
Make sure you're using double quotation (") marks for the f-strings containing the dictionary keys.

Using in Multiline

You can use f-Strings while printing multiline string.
brand = "Ford" msg = ( f"My car is " f"{brand} " f"Mustang" ) print(msg)
Output: My car is Ford Mustang

Display Braces

If you want to make a braces {} appear in your string, you must use double braces in f-string.
print (f"{{Inside braces...}}")
{Inside braces...}

Format specifiers

Inside f-string, format specifiers may also contain evaluated expressions.
from decimal import Decimal width = 10 precision = 4 value = Decimal('14.23456') print (f'Result is : {value:{width}.{precision}}')
Result is : 14.23

f-strings Vs format()

how to python f string
There's a bunch of ways to handle string formatting in Python. f-string strings were introduced to address some of the shortcomings other methods for formatting strings. 3 key reasons why f-Strings are better.
  1. #1 — f-Strings look clean.
  2. #2 — f-Strings are faster.
  3. #3 — f-Strings allow extensive manipulation.
You should use f-Strings whenever possible if you have access to Python 3.6 or later version. Earlier versions don't support f-Strings. Therefore you should consider using format() if you need compatibility with earlier versions.