Reputation: 97
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).
Upvotes: 4
Views: 97
Reputation: 2273
As the type of the age is mixed (str
and int
), just don't specify the type.
for index, name in enumerate(nameAgeDictionary):
print('({0:d}) Name = {1:s}, Age = {2}'.format(index+1, name, nameAgeDictionary[name])) # Format_Method_2
By doing this __str__
of the input should be called which savely converts the int
to str
. The result is:
(1) Name = Jack, Age = 38
(2) Name = John, Age = 51
(3) Name = Alex, Age = 13
(4) Name = Alvin, Age = Not Available
I assume (but I am not completly sure) that in contrast to .format()
the %
formating calles __str__
as fallback.
Update
Here is the proof that %
formating is calling __str__
:
class test():
def __str__(self):
return 'bar'
foo = test()
print('%s'%(foo))
prints
bar
Upvotes: 4