【发布时间】:2016-03-24 14:22:35
【问题描述】:
所以对于我的项目,我必须允许用户输入一个句子,然后输入一个单词并找到该单词的所有出现并打印数字。这就是我所拥有的
found = 0
sen = input("Enter the sentence you would like to break down!")
sen1 = sen.upper()
list = sen1.split()
search=input("Enter the word you want to search")
search1 = search.upper()
for search1 in list:
found = found + 1
position=list.index(search1)
if position == 0:
print("First word in the sentence")
if position == 1:
print("Second word in the sentence")
if position == 2:
print("Third word in the sentence")
if position == 3:
print("Fourth word in the sentence")
if position == 4:
print("Fifth word in the sentence")
if position == 5:
print("6th word in the sentence")
else:
position1 = position + 1
print(position1, "th word in the sentence")
但它只打印单词的第一次出现并且很少起作用。有什么解决办法吗?
【问题讨论】:
-
只是一个注释,你不应该使用变量名
list,因为它是python中的保留字。您正在用自己的变量替换 python 中默认函数的功能,这可能会导致意外结果。你可以看到full list here。 -
list是python中的保留关键字,不应用作变量名。 -
for loop和enumerate()可能是您正在寻找的。span> -
@zephyr:
list不完全是保留字,否则当您尝试重新定义它时会收到 SyntaxError。 (看看如果您尝试分配给for、in或with会发生什么)。但是是的,一个应该避免隐藏像list、str、dict等内置名称。
标签: python