Friday, January 18, 2019

Python Trivia Post: .format() function numbering



Look closely at the code snippet given below - 

days = 8
lyrics = "{} days a week is not enough to love you.But I will not be here {1}"
print(lyrics.format(days,"Sunday"))

Can you guess the output of the program? No. It is not what you are thinking. It is an error code - 


ValueError: cannot switch from automatic field numbering to manual field specification


why? As the .format is like an array of elements. So you have to mention the index number to use or you have to leave the numbering blank, so that it can auto-number. You can not use both formats. So in the above program first call of {} and then {1} lead to the error. you can use {0} and {1}  or leave both the places void.

2 comments:

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...