f-strings in Python

Last Updated : 16 May, 2026

f-strings (formatted string literals) were introduced in Python 3.6 to make string formatting easier and more readable. They allow variables and expressions to be directly embedded inside strings using curly braces {}.

Python
name = "Emily"
age = 20
print(f"My name is {name} and I am {age} years old")

Output
My name is Emily and I am 20 years old

Syntax

An f-string is created by adding f before the string and placing variables or expressions inside {}.

f"{variable/expression}"

Examples

Example 1: This example formats and prints the current date using an f-string.

Python
import datetime
today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")

Output
May 09, 2026

Explanation:

  • datetime.datetime.today() gets the current date.
  • %B, %d and %Y format the month, day and year.
  • f-string inserts the formatted date into the string.

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

Example 2: This example shows how single, double and triple quotes can be used in f-strings.

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

Output
'GeeksforGeeks'
Geeks"for"Geeks
Geeks'for'Geeks

Explanation:

  • f-strings support single, double and triple quotes. Different quote styles help avoid syntax errors.
  • Triple quotes allow quotes to be used easily inside strings.

Example 3: This example evaluates an expression directly inside an f-string.

Python
Physics = 78
Chemistry = 56
Biology = 85
print(f"Alex got total marks {Physics + Chemistry + Biology} out of 300")

Output
Alex got total marks 219 out of 300

Errors while Using f-strings

1. Missing Closing Braces: Every opening curly brace { in an f-string must have a matching closing brace }.

Python
name = "Jake"
print(f"My name is {name")

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 2
print(f"My name is {name")
^
SyntaxError: f-string: expecting '}'

2. Using Undefined Variables: Variables used inside an f-string must be defined before they are used.

Python
print(f"My age is {age}")

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
NameError: name 'age' is not defined

Comment