Change language

f-strings in Python 3 — formatted string literals


To create an f-string, add a string with the letter "f". The string itself can be formatted in much the same way as

# Python3 program representing the 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. " )


 Hello, My name is Tushar and I’m 23 years old. Python.Engineering is a portal for Geeks. 

Code # 2:

# Prints today’s date with
# time and date libraries

import datetime


today = ()

print (f "{today:% B% d,% Y}" )


 April 04, 2018 

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

Y Let’s take a look at a few examples of errors that can occur when using an f-line:

Code # 3: Demonstrate a syntax error.

answer = 456

f "Your answer is" {answer} ""

Code # 4: The backslash cannot be used directly in a format string.

f " newline: {ord (’’)} "


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

But the documentation indicates that we can put a backslash in a variable as a workaround:

newline = ord ( ’’ )


f "newline: {newline}"


 newline: 10 

Link: PEP 498, Literal String Interpolation

f-strings in Python 3 — formatted string literals Python functions: Questions

f-strings in Python 3 — formatted string literals String Variables: Questions


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Best laptop for Zoom


Best laptop for Minecraft


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method