为什么不同的格式化方法在 Python 中表现不同?

Why different format method behave differently in Python?

我是 Python 作为初学者学习的。最近我学习了格式化方法,字典等。目前我正在研究for循环并发现了一个名为enumerate的函数(可能与问题无关)。我通过混合所有东西来应用我到目前为止学到的东西。突然发现两种格式化方法的作用是不一样的!!这是怎么发生的,为什么会发生?请解释。

方法一:

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

输出:

(1) 姓名 = Jack,年龄 = 38

(2) 姓名 = 约翰,年龄 = 51

(3) 姓名 = Alex,年龄 = 13

(4) 姓名 = Alvin,年龄 = 不可用

方法二:

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

输出:

回溯(最后一次调用): 文件“PATH_to_File.py”,第 3 行,在

print('({0:d}) 姓名 = {1:s}, 年龄 = {2:s}'.format(

ValueError:'int'

类型对象的未知格式代码 's'

我试过用 d 代替 s,在这种情况下,它打印前 3 行并卡在最后一行(例如不可用)。

由于年龄的类型是混合的(strint),所以不要指定类型。

for index, name in enumerate(nameAgeDictionary):
    print('({0:d}) Name = {1:s}, Age = {2}'.format(index+1, name, nameAgeDictionary[name])) # Format_Method_2

通过执行此操作,应调用输入的 __str__,从而将 int 安全地转换为 str。结果是:

(1) Name = Jack, Age = 38
(2) Name = John, Age = 51
(3) Name = Alex, Age = 13
(4) Name = Alvin, Age = Not Available

我假设(但我不完全确定)与 .format() 相比,% 格式化调用 __str__ 作为后备。

更新

这是%格式化调用__str__的证明:

class test():
     def __str__(self):
         return 'bar'
 
foo = test()
print('%s'%(foo))

打印

bar