In Python, we can use the format() method to format a string. We first define a string using format fields in the following way:
s1 = "{} {}! How are you?" s2 = "Hi {0} and {1}! Welcome!"
And, then, we call the format() method to replace the format fields within the string.
s1 = "{} {}! How are you?" print(s1.format("Hi", "John")) s2 = "Hi {0} and {1}! Welcome!" print(s2.format("Alice", "Bob"))
In the string s1, we are using only brackets as format fields. So, the first format field will be replaced by “Hi” and the second format field will be replaced by “John”.
In the string s2, we are using a number within brackets to indicate a format field. So, the first format field will be replaced by Alice and the second format field will be replaced by Bob. The program will print the following output:
Hi John! How are you? Hi Alice and Bob! Welcome!
We can use the numbers within the brackets in any order to indicate a format field. For example,
s = "Hi {1} and {0}! Welcome!" print(s.format("Alice", "Bob"))
The program will print the following output:
0 Comments