单词列表存储返回“字符串索引超出范围”。为什么?

时间:2018-10-20 17:34:37

标签: python string list indexing

我正在做一个作业,我们必须要求用户输入一个单词,然后如果该单词的字母重复该单词中的首字母,例如:ApplesAuce(A重复),程序将将单词存储在列表中,然后在用户输入完单词后打印出列表。

我收到此错误

  

如果word [1:]。lower()中的word [0] .lower():IndexError:字符串索引输出   范围

这是我的代码:

wordlist = [] 
word = input("Please enter a hilariously long word: ")
# I said "hilariously long" to increase the likelihood of a repeat letter
while wordlist != '':
    word = input("Please enter another hilariously long word: ")
    if word[0].lower() in word[1:].lower():
        wordlist.append(word) 

word = input("Please enter another hilariously long word: ")

print("All of the words that had repeated first letters are: ")
print(wordlist)

2 个答案:

答案 0 :(得分:0)

测试单词是否存在,如果不存在则跳出while循环。

wordlist = []
msg = "Please enter a hilariously long word: "
# I said "hilariously long" to increase the likelihood of a repeat letter
while True:
    word = input(msg)
    if word:
        if word[0].lower() in word[1:].lower():
            wordlist.append(word)
    else:
        break

print("All of the words that had repeated first letters are: ")
print(wordlist)

还要注意,wordlistlist,因此测试while wordlist != ""总是如此,因为list不是string

答案 1 :(得分:0)

这应该工作。我已经介绍了已退出或已完成的断路器,它将打破循环。我也将您的第一个输入移到其中,如果填充了单词表,则会添加另一个输入。

wordlist = [] 
# I said "hilariously long" to increase the likelihood of a repeat letter
while 1:
    word = input("Please enter {}hilariously long word: ".format('another ' if wordlist else ''))

    # get out if done or quit is typed
    if word in ('done','quit'):
        break
    if word[0].lower() in word[1:].lower():
        wordlist.append(word) 

print("All of the words that had repeated first letters are: ")
print(wordlist)