Contents

What will be the output of the following Python code snippet?
X=”hi”
print(“05d”%X)
a) 00000hi                           
b) 000hi
c) hi000                                
d) error

d

Explanation: The code snippet shown above results in an error because the above formatting option works only if ‘X’ is a number. Since in the above case ‘X’ is a string, an error is thrown.


What will be the output of the following Python code snippet?
X=”san-foundry”
print(“%56s”,X)
a) 56 blank spaces before san-foundry
b) 56 blank spaces before san and foundry
c) 56 blank spaces after san-foundry
d) no change

a

Explanation: The formatting option print(“%Ns”,X) helps us add ‘N’ number of spaces before a given string ‘X’. Hence the output for the code snippet shown above will be 56 blank spaces before the string “san-foundry”.


What will be the output of the following Python expression if x=456?
print("%-06d"%x)
a) 000456                            
b) 456000
c) 456                                    
d) error

c

Explanation: The expression shown above results in the output 456.


What will be the output of the following Python expression if X=345?
print(“%06d”%X)
a) 345000                            
b) 000345
c) 000000345                      
d) 345000000

b

Explanation: The above expression returns the output 000345. It adds the required number of zeroes before the given number in order to make the number of digits 6 (as specified in this case).


Which of the following formatting options can be used in order to add ‘n’ blank spaces after a given string ‘S’?
a) print(“-ns”%S)
b) print(“-ns”%S)
c) print(“%ns”%S)              
d) print(“%-ns”%S)

d

Explanation: In order to add ‘n’ blank spaces after a given string ‘S’, we use the formatting option:(“%-ns”%S).


What will be the output of the following Python expression if X = -122?
print("-%06d"%x)
a) -000122                           
b) 000122
c) –00122                             
d) -00122

c

Explanation: The given number is -122. Here the total number of digits (including the negative sign) should be 6 according to the expression. In addition to this, there is a negative sign in the given expression. Hence the output will be – -00122.