31. What will be the output of the following Python code?
‘{a}{b}{a}’.format(a=’hello’, b=’world’)
a) ‘hello world’
b) ‘hello’ ‘world’ ‘hello’
c) ‘helloworldhello’
d) ‘hello’ ‘hello’ ‘world’
Check Answer
Answer: c
The code shown above prints the values substituted for a, b, a, in the same order. This operation is performed using the format function. Hence the output of the code is: ‘helloworldhello’.
32. What will be the output of the following Python code?
D=dict(p=’py’, q=’thon’)
‘{p}{q}’.format(**D)
a) Error
b) python
c) py thon
d) {‘py’, ‘thon’}
Check Answer
Answer: b
The code shown above prints the values substituted for p and q in the same order. Note that there is no blank space between p and q. Hence the output is: sanfoundry.
33. What will be the output of the following Python code?
‘The {} side {1} {2}’.format(‘bright’, ‘of’, ‘life’)
a) Error
b) ‘The bright side of life’
c) ‘The {bright} side {of} {life}’
d) No output
Check Answer
Answer: a
The code shown above results in an error. This is because we have switched from automatic field numbering to manual field numbering, that is, from {} to {1}. Hence this code results in an error.
34. What will be the output of the following Python code?
‘{0:f}, {1:2f}, {2:05.2f}’.format(1.23456, 1.23456, 1.23456)
a) Error
b) ‘1.234560, 1.22345, 1.23’
c) No output
d) ‘1.234560, 1.234560, 01.23’
Check Answer
Answer: d
In the code shown above, various formatting options are displayed using the format option. Hence the output of this code is: ‘1.234560, 1.234560, 01.23’
35. What will be the output of the following Python code?
‘%.2f%s’ % (1.2345, 99)
a) ‘1.2345’, ‘99’
b) ‘1.2399’
c) ‘1.234599’
d) 1.23, 99
Check Answer
Answer: b
In this code, we must notice that since multiple values haven been given, they should be enclosed in a tuple. Since the formatting format is %.2f, the value 1.2345 is reduced to two decimal places. Hence the output of the code shown above: ‘1.2399’.
36. What will be the output of the following Python code?
‘%s’ %((1.23,),)
a) ‘(1.23,)’
b) 1.23,
c) (,1.23)
d) ‘1.23’
Check Answer
Answer: a
The formatting expression accepts either a single substitution value, or a tuple of one or more items. Since single item can be given either by itself or within the tuple, a tuple to be formatted must be provided as a tested tuple. Hence the output of the code is: >>> ‘%s’ %((1.23,),).
37. What will be the output of the following two codes?
i. ‘{0}’.format(4.56)
ii. ‘{0}’.format([4.56,])
a) ‘4.56’, ‘4.56,’
b) ‘4.56’, ‘[4.56]’
c) 4.56, [4.56,]
d) 4.56, [4.56,]
Check Answer
Answer: b
The code shown above shows the formatting option on the same value, that is 4.56, where in the second case, the value is enclosed in a list. Hence the output of the code shown above is:
‘4.56’, ‘[4.56]’