首页 > 解决方案 > 如何在 Python 中使用 .format() 在“for”循环中打印列表?

问题描述

我是 Python 的新手。我正在编写一段非常简单的代码来使用'for'循环打印列表的内容,.format()我希望输出如下,但我收到了这个错误:

names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
    print("{}.{}".format(i, names[i])) 

print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str

我想要的预期输出:1. David 2. Peter 3. Michael 4. John 5. Bob

有人可以帮我得到那个输出吗?

标签: pythonlistfor-loopstring.format

解决方案


names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
    print("{}.{}".format(i + 1, names[i]))

Python 列表索引引用不能是字符串。使用整数而不是索引本身(它们是字符串)通过 for 循环遍历列表将解决此问题。这是一个错误消息在诊断问题时非常有用的示例。


推荐阅读