String formatting in Python

May 13, 2021, 10 p.m.


There are three ways for string formatting in Python:
1) .format()
2) Using template
3) Using template with dictionary

There are three ways for string formatting in Python:
1) .format()
2) Using template
3) Using template with dictionary

from string import Template
str1="He scored {0} in {1} balls".format(200,147)
print(str1)

str2="He scored {runs} in {balls} balls".format(runs=200,balls=147)
print(str2)

temp = Template("${name} made ${runs} runs in ${matches} matches in the 2003 Cricket World Cup")
str3=temp.substitute(name="Sachin Tendulkar", runs=673,matches=11)
print(str3)

data = {
    "name":"Sachin Tendulkar",
    "matches":11,
    "runs":673
}
str4= temp.substitute(data)
print(str4)
He scored 200 in 147 balls
He scored 200 in 147 balls
Sachin Tendulkar made 673 runs in 11 matches in the 2003 Cricket World Cup
Sachin Tendulkar made 673 runs in 11 matches in the 2003 Cricket World Cup

 



Tags


Comments