Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make string interpolation simpler.
How to use f-strings in Python
To create an f-string, prefix the string with the letter “f“. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.Â
In the below example, we have used the f-string inside a print() functions/method to print a string. We use curly braces to use a variable value inside f-strings, so we define a variable ‘val’ with ‘Geeks’ and use this inside when seen in the code below ‘val’ with ‘Geeks’. Similarly, we use the ‘name’ and the variable inside a second print statement.
# Python3 program introducing f-string
val = 'Code-Config'
str='Coders'
print(f"{val} is a portal for {str}.")
name = 'Sham'
age = 32
print(f"Hello, my name is {name} and I'm {age} years old.")
Output
In this example, we have printed today’s date using the datetime module in Python with f-string. For that firstly, we import the datetime module after that we print the date using f-sting. Inside f-string ‘today’ assigned the current date and %B, %d, and %Y represents the full month, day of month, and year respectively.
# Prints today's date with help
# of datetime library
import datetime
today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")
Output
Note: F-strings are faster than the two most commonly have used string formatting mechanisms, which are % formatting and str.format().
To use any type of quotation marks with the f-string in Python we have to make sure that the quotation marks have used inside the expression are not the same when quotation marks have used with the f-string.
print(f"'CodeConfig'")
print(f"""code"for"fun""")
print(f'''code'for'fun''')
Output
We can also evaluate expressions with f-strings in Python. To do so we have to write the expression inside the curly braces in f-string and the evaluated result will be printed when shown in the below code’s output.
english = 80
maths = 60
hindi = 80
print(f"Mohan got total marks {english + Maths + Hindi} out of 300")
Output
Errors when using f-string in Python
In Python f-string, Backslash Cannot be have used in format string directly.
f"newline: {ord('\n')"
Output
However, we can put the backslash into a variable when a workaround over:
newline = ord('\n')
print(f"newline: {newline}")