Python f-strings - How to insert variables into a string

The Python f-strings enables inserting variables in a string. The f prefix represents f-string.

a = 'HTML'
b = 'CSS'

c = 'I study {a} and {b}.'
d = f'I study {a} and {b}.'

print(c)  # I study {a} and {b}.
print(d)  # I study HTML and CSS.

c is a "normal" string and {a} is interpreted literally. d is a f-string and a in the curly brackets is interpreted as a variable and replaced with HTML. You can set multiple variables in a string. The f prefix means "formatted".

Double quotes can be a f-string

a = "Java"
b = 'C++'

s = f"I love {a} and {b}."
t = "I love {0} and {1}.".format(a, b)

print(s)  # I love Java and C++.
print(t)  # I love Java and C++.

Double quotes can represent a f-string in Python. You can do the same using the format().

Three double quotes

a = "Java"
b = 'C++'

s = f"""
I love

{a}

and

{b}.
"""

print(s)
#
# I love
#
# Java
#
# and
#
# C++.
#

You can insert newlines into a string using three double quotes as explained in this article.

Python String

Python Tutorial