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

2024-09-30 22:28:39 发布

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

我正在做一个任务,我们必须要求用户输入一个单词,然后如果单词中有一个字母重复单词中的首字母,例如:ApplesAuce(a repeats),程序会将单词存储在列表中,然后在用户输入完单词后打印出列表。你知道吗

我得到这个错误

if word[0].lower() in word[1:].lower(): IndexError: string index out of range

这是我的密码:

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)

Tags: ofthe用户in列表inputif单词
2条回答

这应该是工作。我介绍了断路器是退出或完成将打破循环。我也移动了你的第一个输入里面,将添加另一个如果wordlist填充。你知道吗

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)

测试一个单词是否存在,如果不存在,就跳出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

相关问题 更多 >