I was learning Python as a beginner. Recently I learnt about formatting methods, dictionaries and etc. Currently I was studying for loop and discovered a functioned called enumerate (probably nothing to do with is problem). I was applying what I had learnt till now by mixing everything. Suddenly I discovered that two format method acts differently!! How and why is this happening? Please explain.
Method 1:
nameAgeDictionary = {'Jack': 38, 'John': 51, 'Alex': 13, 'Alvin': 'Not Available'}
for index, name in enumerate(nameAgeDictionary):
print('(%d) Name = %s, Age = %s' % (index+1, name, nameAgeDictionary[name])) # Format_Method_1
Output:
(1) Name = Jack, Age = 38
(2) Name = John, Age = 51
(3) Name = Alex, Age = 13
(4) Name = Alvin, Age = Not Available
Method 2:
nameAgeDictionary = {'Jack': 38, 'John': 51, 'Alex': 13, 'Alvin': 'Not Available'}
for index, name in enumerate(nameAgeDictionary):
print('({0:d}) Name = {1:s}, Age = {2:s}'.format(index+1, name, nameAgeDictionary[name])) # Format_Method_2
Output:
Traceback (most recent call last): File "PATH_to_File.py", line 3, in
print('({0:d}) Name = {1:s}, Age = {2:s}'.format(
ValueError: Unknown format code 's' for object of type 'int'
I have tried putting d in the place of s, on that case, it prints first 3 lines and gets stucked in last line (e.g. Not Available).
strwith!.print('({0:d}) Name = {1:s}, Age = {2!s}'.format(index+1, name, nameAgeDictionary[name]))