Python provides several ways to format strings. In this article, we will discuss the following methods for string formatting in Python:
- Using the string template class
- Using the % operator
- Using the format() method
- Using f-strings
String Template Class
The string template class in Python allows you to substitute or inject variable values within strings. To make use of the template class, you must first import it from the string module using the following line of code:
from string import Template
To use the template class to format strings, you need to create a string containing placeholders using the $ operator. For example:
template_string = Template("My name is $name! I create content on $language")
You can then substitute values for the placeholders using the substitute() method, as shown below:
output = template_string.substitute(name="ABDULLAH", language="Python")
This will replace the placeholders with the values provided and output the resulting string:
My name is ABDULLAH! I create content on Python
The % Operator
For example:
name = "John"
age = 80
print("%s is %d years old" %(name, age))
This will output:
John is 80 years old
The format() Method
The format() method is another way to format strings in Python. Instead of using placeholders, you use curly brackets {} to substitute the parameters of the format() method.
For example:
name = "John"
age = 80
print("{} is {} years old".format(name, age))
This will output:
John is 80 years old
F-strings
F-strings are a newer way to format strings in Python. They use curly brackets {} to substitute variables directly into a string. To use f-strings, simply place an f before the opening quotation mark of the string.
For example:
name = "John"
age = 80
print(f"{name} is {age} years old")
This will output:
John is 80 years old
You can also perform arithmetic operations
within the curly brackets of an f-string:
num1 = 20
num2 = 80
print(f"{num1} + {num2} = {num1 + num2}")
This will output:
20 + 80 = 100
Conclusion
In summary, Python provides several ways to format strings, including the string template class, the % operator, the format() method, and f-strings. Each method has its own advantages and can be used depending on the specific requirements of the program.


