dev*_*hon 4 python string.format for-loop list
我是 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
有人可以帮我得到那个输出吗?
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
Run Code Online (Sandbox Code Playgroud)
Python 列表索引引用不能是字符串。使用整数而不是索引本身(字符串)通过 for 循环迭代列表将解决此问题。在这个示例中,错误消息对于诊断问题非常有用。