Understand Python f-string with Examples – Python Tutorial

By | March 22, 2023

In order to format a python string, we can use % operation, here is the tutorial:

A Simple Guide to Python String Formatting for Python Beginners – Python String Tutorial

However, we also can use f-string to do. In this tutorial, we will use some examples to show you how to do.

How to print a text string in python?

We can use these methods to print a text string.

print("my age is "+str(age))
print("my age is %d" % age)
print("my age is {}".format(age))

Three methods above are not easy, we can see:

my age is 10
my age is 10
my age is 10

How to use python f-string?

f-string is defined as:

f”string”

We can use it to print a string that contains variables.

f”{variable_name}”

For example:

age = 10
name = "tom"
print(f"my age is {age}")
print(f"my name is {name} and age is {age}")

Then, we will get:

my age is 10
my name is tom and age is 10

It is very easy.