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

标签 python python-3.x for-loop formatting format

我作为初学者学习 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}) Name = {1:s}, Age = {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__输入的应该被调用,它可以节省转换 intstr .结果是:
(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

关于python - 为什么不同的格式方法在 Python 中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67510291/

相关文章:

python - 如何找出 pandas groupby 对象中唯一行的数量?

python添加二进制数

python - BeautifulSoup页面抓取时出现KeyError

python - 迭代 Groupby.unstack() 项以制作单独的图

PHP:仅执行for循环来显示html

python - 在 Python 中排除正则表达式内的字符序列(不仅是单个字符)

python - 未实现错误 : file structure not yet supported from pandas read_csv

python - url_for 使用 & 创建一个 url 查询字符串

r - 我将如何创建这个数据框?我需要使用嵌套 for 循环吗?

python - 来自现有列和查找表的新插值列