将输入限制为一个单词

时间:2016-12-03 11:44:06

标签: python-3.x

所以这是我的代码:

sentence=input('Please input a sentence: ').lower()
word=input('What word would you like to select? ').lower()
words=sentence.split()
for (A, keyword) in enumerate(words):
    if(keyword==word):
        print(A+1)
if(keyword!=word):
        print ('This word is not in the sentence')

我需要将用户输入限制为只有一个单词并在输入2个单词时返回错误消息,我该怎么做?

1 个答案:

答案 0 :(得分:0)

检查分割输入的长度是否大于1:

word = input('What word would you like to select? ').lower()
if len(word.split()) > 1:
    raise Exception("Input must be a single word")