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
Comments
Post a Comment