In this tutorial, we will introduce 3 methods to format a python string.
1.Use % Operator
Here is an exmaple:
num = 12 result = num * num str = "The square of %d is %d" % (num, result) print(str)
Run this code, you will see:
The square of 12 is 144
2.Use f-strings
For example:
num = 12 result = num * num str = f"The square of {num} is {result}" print(str)
Run this code, you will see:
The square of 12 is 144
Expressions also can be used in f-string.
Here is an example:
a = 1 b = 2 str = f"Expression: {a + b}" print(str)
Run this code, you will see:
Expression: 3
3.Use string.format() method
Here is an example:
num = 12 result = num * num str = "The square of {} is {}".format(num, result) print(str)
The output is:
The square of 12 is 144
You also can use name to format a string using string.format().
Here is an example:
a = 1 b = 2 str = "a is '{first}' and b is '{second:03}'".format(first=a, second=b) print(str)
Run this code, you will get the output:
a is '1' and b is '002'