小编dev*_*hon的帖子

如何在 Python 中使用 .format() 打印“for”循环中的列表?

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

names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
    print("{}.{}".format(i, names[i])) 
Run Code Online (Sandbox Code Playgroud)
print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str
Run Code Online (Sandbox Code Playgroud)

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

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

python string.format for-loop list

4
推荐指数
1
解决办法
5万
查看次数

标签 统计

for-loop ×1

list ×1

python ×1

string.format ×1