【问题标题】:String index out of range error when creating a palindrome program创建回文程序时出现字符串索引超出范围错误
【发布时间】:2019-12-04 11:51:35
【问题描述】:

我是一名初级程序员,我尝试创建一个程序来检查输入的单词是否为回文,但我不断收到此字符串索引超出范围错误,我不知道为什么。

word= input("enter word")
    for i in range(0, len(word)):
        if word[i] == word[len(word) - i]:
            count+=1
if count == len(word):
    print("yes it is")
else:
     print("no it is not")

【问题讨论】:

    标签: python string loops for-loop indexing


    【解决方案1】:
    word[len(word) - i]
    

    假设word"hello",您将拥有word[5 - i],并且由于i 为0,您将拥有超出范围的word[5](有效索引为0、1、2、 3、4)。所以你需要

    if word[i] == word[len(word) - 1 - i]:
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2017-03-11
      • 2013-09-25
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多