VOOZH about

URL: https://www.geeksforgeeks.org/python/formatted-string-literals-f-strings-python/

⇱ f-strings in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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 {}.


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.


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.


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.


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 }.

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.

Output

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

Comment
Article Tags:
Article Tags: