lis中的格式化字符串

2024-04-19 01:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

它的解决方案是什么? 我写了一个字符串列表,如前所示,我想格式化它并包括选项,然后我想打印(通过从用户输入)它的索引,但在终端错误抛出0或1索引不存在于列表中。你知道吗

options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options.index(1)}",
              f"Physics is the study of .......\n{options.index(2)}"]

q_1 = input(questions[0])

Tags: andof字符串用户终端列表indexis
2条回答

options.index(1)在列表中搜索1,并返回其索引。这不是你想要的。你知道吗

您似乎想要获得options的第一个元素,而这是用options[0]完成的。你知道吗

它是0而不是1,因为Python列表的索引是从0开始的,而不是从1开始的。你知道吗

当索引到questions时,您做的是正确的。你知道吗

我已经用选项[1]而不是选项.索引(一)

options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options[0]}", f"Physics is the study of .......\n{options[1]}"]

q_1 = input(questions[0])

index方法搜索您提供的值是否在列表中选项.索引(0)检查值为0的元素是否存在并返回其索引

要获取索引0处的元素,请使用list[0]

相关问题 更多 >