In: Computer Science
3. Show the string that would result from each of the following string formatting operations. If the operation is not legal, explain why. Use Python shell to solve this question
(a) "Looks like {1} and {0} for breakfast".format("eggs", "spam") =>
(b) "There is {0} {1} {2} {3}".format(1,"spam", 4, "you") =>
(c) "Hello {0}".format("Susan", "Computewell") =>
(d) "{0:0.2f} {0:0.2f}".format(2.3, 2.3468) =>
(e) "{7.5f} {7.5f}".format(2.3, 2.3468) =>
(f) "Time left {0:02}:{1:05.2f}".format(1, 37.374) =>
(g) "{1:3}".format("14") =>
Question 3:
Show the string that would result from each of the following string
formatting operations. If the operation is not legal, explain why.
Use Python shell to solve this question
(a) "Looks like {1} and {0} for breakfast".format("eggs",
"spam")
Ans: Legal
This is the correct way of using the format() method. The placeholders is defined using curly brackets{} and then we provide values for the following placeholders as parameters to that format() method.
(b) "There is {0} {1} {2} {3}".format(1,"spam", 4, "you")
=>
Ans: Legal
This is also the correct way of using the format() method, we can use any data type as a parameter to the method format().
(c) "Hello {0}".format("Susan", "Computewell") =>
Ans: Legal
There can be any number of parameters for the method format(). It is necessary to use all those mentioned parameters.
(d) "{0:0.2f} {0:0.2f}".format(2.3, 2.3468) =>
Ans: Legal
We can even use the same placeholder twice. This is also valid.
(e) "{7.5f} {7.5f}".format(2.3, 2.3468) =>
Ans: Illegal
This is because the interpreter assumes the value inside the placeholder to an index. As we can see from the expression, we have used the index 7 for that, the number of arguments to the format() should be 8 accordingly. Since we don't have 8 values or 8 parameters in the format(). It raises an error stating the tuple index out of range.
(f) "Time left {0:02}:{1:05.2f}".format(1, 37.374) =>
Ans: Legal
Here, if we consider the statement. we notice that {0:02} indicates the first argument(0th index) with a field width of 2 and {1:05.2f} indicates the second argument(1st index/ with 2 decimal places of precision.
(g) "{1:3}".format("14") =>
Ans: Illegal
This is because, if we consider the statement {1:3} indicates a second argument with a field of width 3. Since there is no second argument. It raises an IndexError exception.
Please check the
compiled program and its output for your reference which is done in
Python shell:
(Feel free to drop me a comment, If you need any help)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...