What will be the output of the following Python code?
s='{0}, {1}, and {2}'
s.format('hello', 'good', 'morning')
a) ‘hello good and morning’
b) ‘hello, good, morning’
c) ‘hello, good, and morning’
d) Error
Explanation: Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position or keyword. Hence the output of the code shown above:’hello, good,and morning’.
What will be the output of the following Python code?
t = '%(a)s, %(b)s, %(c)s'
t % dict(a='hello', b='world', c='universe')
a) ‘hello, world, universe’
b) ‘hellos, worlds, universes’
c) Error
d) hellos, world, universe
Explanation: Within the subject string, curly braces represent substitution targets and arguments to be inserted. Hence the output of the code shown above:
‘hello, world, universe’.
What will be the output of the following Python code?
'{a}, {0}, {abc}'.format(10, a=2.5, abc=[1, 2])
a) Error
b) ‘2.5, 10, [1, 2]’
c) 2.5, 10, 1, 2
d) ’10, 2.5, [1, 2]’
Explanation: Since we have specified that the order of the output be: {a}, {0}, {abc}, hence the value of associated with {a} is printed first followed by that of {0} and {abc}. Hence the output of the code shown above is: ‘2.5, 10, [1, 2]’.
What will be the output of the following Python code?
'{0:.2f}'.format(1.234)
a) ‘1’
b) ‘1.234’
c) ‘1.23’
d) ‘1.2’
Explanation: The code shown above displays the string method to round off a given decimal number to two decimal places. Hence the output of the code is: ‘1.23’.
What will be the output of the following Python code?
'%x %d' %(255, 255)
a) ‘ff, 255’
b) ‘255, 255’
c) ‘15f, 15f’
d) Error
Explanation: The code shown above converts the given arguments to hexadecimal and decimal values and prints the result. This is done using the format specifiers %x and %d respectively. Hence the output of the code shown above is: ‘ff, 255’.
The output of the two codes shown below is the same.
i. '{0:.2f}'.format(1/3.0)
ii. '%.2f'%(1/3.0)
a) True
b) False
Explanation: The two codes shown above represent the same operation but in different formats. The output of both of these functions is: ‘0.33’. Hence the statement is true.