Before Python 3.6, there were two basic tools for interpolating (mixing) values, variables, and expressions within string literals:
1 — The string interpolation operator (%) (the math’s modulo operator)
2 — The string.format() method
This article talks about the second one — format() of string (str) class for string formatting.
format() method
The str.format()
approach is superior to the % operator because it addresses a few shortcomings and supports the string formatting mini-language.
To make the .format()
method work, you must specify replacement fields in curly brackets. If you provide empty brackets, the method will interpolate its arguments into the target string based on their position.
Code:
stu_name = "Akhanda"
stu_age = 35
stu_fee = 2562
str ="Name: {} , Age: {}, Fee: {} "
print (str.format(stu_name, stu_age, stu_fee ))
Output:
Name: Akhanda , Age: 35, Fee: 2562
The last two lines of code can be combined in a single print statement.
print("Name: {} , Age: {}, Fee: {} ".format(stu_name, stu_age, stu_fee) )