Open In App

f-strings in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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. 

Print Variables using f-string in Python

In the below example, we have used the f-string inside a print() 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 as seen in the code below ‘val’ with ‘Geeks’. Similarly, we use the ‘name’ and the variable inside a second print statement.

Python




# Python3 program introducing f-string
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
 
 
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")


Output

GeeksforGeeks is a portal for Geeks.
Hello, My name is Tushar and I'm 23 years old.

Print date using f-string in Python

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.

Python




# Prints today's date with help
# of datetime library
import datetime
 
today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")


Output

March 06, 2024

Note: F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). 

Quotation Marks in f-string in Python

To use any type of quotation marks with the f-string in Python we have to make sure that the quotation marks used inside the expression are not the same as quotation marks used with the f-string.

Python




print(f"'GeeksforGeeks'")
 
print(f"""Geeks"for"Geeks""")
 
print(f'''Geeks'for'Geeks''')


Output

print(f"'GeeksforGeeks'")print(f"""Geeks"for"Geeks""")print(f'''Geeks'for'Geeks''')

Evaluate Expressions with f-Strings in Python

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 as shown in the below code’s output.

Python




english = 78
maths = 56
hindi = 85
 
print(f"Ram got total marks {english + maths + hindi} out of 300")


Output

Ram got total marks 219 out of 300

Errors while using f-string in Python

Backslashes in f-string in Python

In Python f-string, Backslash Cannot be used in format string directly.

Python




f"newline: {ord('\n')"


Output

Traceback (most recent call last):
  Python Shell, prompt 29, line 1
Syntax Error: f-string expression part cannot include a backslash: , line 1, pos 0

However, we can put the backslash into a variable as a workaround though :

Python




newline = ord('\n')
 
print(f"newline: {newline}")


Output

newline: 10

Inline comments in f-string in Python

We cannot use comments inside F-string expressions. It will give an error:

Python




f"GeeksforGeeks is {5*2 + 3 #geeks-5} characters."


Output:

Hangup (SIGHUP)
  File "Solution.py", line 1
    f"GeeksforGeeks is {5*2 + 3 #geeks-5} characters."
    ^
SyntaxError: f-string expression part cannot include '#'

Printing Braces using f-string in Python

If we want to show curly braces in the f-string’s output then we have to use double curly braces in the f-string. Note that for each single pair of braces, we need to type double braces as seen in the below code.

Python




# Printing single braces
print(f"{{Hello, Geek}}")
 
# Printing double braces
print(f"{{{{Hello, Geek}}}}")


Output

{Hello, Geek}
{{Hello, Geek}}

Printing Dictionaries key-value using f-string in Python

While working with dictionaries, we have to make sure that if we are using double quotes (“) with the f-string then we have to use single quote (‘) for keys inside the f-string in Python and vice-versa. Otherwise, it will throw a syntax error.

Python




Geek = { 'Id': 112,
         'Name': 'Harsh'}
 
print(f"Id of {Geek["Name"]} is {Geek["Id"]}")


Output

Hangup (SIGHUP)
  File "Solution.py", line 4
    print(f"Id of {Geek["Name"]} is {Geek["Id"]}")
                            ^
SyntaxError: invalid syntax

Using the same type of quotes for f-string and key

Python




Geek = { 'Id': 112,
         'Name': 'Harsh'}
 
print(f"Id of {Geek['Name']} is {Geek['Id']}")


Output

Id of Harsh is 112


Last Updated : 06 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads