每当我试着输入一个字母,在句子中它不起作用?

时间:2016-04-21 09:57:29

标签: python

sentence = ("ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO       FOR YOUR COUNTRY")


print (sentence)

keyword = input("Input a word from the sentence")

keyword_check = True

words = sentence.split(' ')

while keyword_check == True:
for w in range(len(keyword)):
    if keyword[w].isalpha():
        keyword = keyword.lower()

if keyword not in sentence:
    keyword = input("please enter a valid word")

else:

    for (i, subword) in enumerate(words):
        if (subword == keyword):
            print("your word is in position")
            print(i+1)
            keyword_check = False

正如标题所说,当我尝试输入句子中的一封信时会停止该程序,如果我不输入任何内容,它也会停止程序帮助!

1 个答案:

答案 0 :(得分:0)

在Python2中input相当于eval(raw_input(prompt)),因此您的输入将被评估。不是你想要的例子。使用raw_input将用户输入作为字符串。

只需使用split()来分割你的句子。它使用空格作为分隔符,可以更好地处理句子中的多个空格。

对于比较,知道在哪个位置使用lower()忽略套管总是一件好事。

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO       FOR YOUR COUNTRY"
print(sentence)
words=sentence.lower().split()

while True:
  keyword = raw_input("Input a word from the sentence: ").lower()
  try:
    index=words.index(keyword)
  except ValueError: # is raised, when keyword is not found in words
    continue
  break

print("Found on index: %d"%words.index(keyword))

在回答你的问题时,我觉得我已经完成了你的功课了吗?