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.

  1. print("my age is "+str(age))
  2. print("my age is %d" % age)
  3. print("my age is {}".format(age))
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:

  1. my age is 10
  2. my age is 10
  3. my age is 10
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:

  1. age = 10
  2. name = "tom"
  3. print(f"my age is {age}")
  4. print(f"my name is {name} and age is {age}")
age = 10
name = "tom"
print(f"my age is {age}")
print(f"my name is {name} and age is {age}")

Then, we will get:

  1. my age is 10
  2. my name is tom and age is 10
my age is 10
my name is tom and age is 10

It is very easy.