String Formatting in Python

 

Concept


In Python below code will create an 'Type Error' because python does not support this kind of operation.

age = 36
txt = "My name is John, I am " + age
print(txt) 

Output: TypeError: must be str, not int

So get rid of this issue we basically do 'String Formatting' by using format() method.


 

Code


Example 1:

txt = "I love {} & {}"
print(txt.format('Python', 'Django'))

Output: I love Python & Django

 

Example 2:

txt = "I love {0} & {1}"
print(txt.format('Python', 'Django'))

Output: I love Python & Django

 

Example 3:

txt = "I love {1} & {0}"
print(txt.format('Python', 'Django'))

Output: I love Django & Python

 

Example 4:

txt = "I love {x} & {y}"
print(txt.format(x='Python', y='Django'))

Output: I love Python & Django




Get Help

Comments

Popular posts from this blog

How To Create .ENV File in Python

Create a Large file for Test Data Processing using Python

How to solve the Liner Equation using Python