【问题标题】:Beginner Issue; string index out of range初学者问题;字符串索引超出范围
【发布时间】:2015-08-07 20:56:44
【问题描述】:
# word reverser
#user input word is printed backwards

word = input("please type a word")

#letters are to be added to "reverse" creating a new string each time
reverse = ""

#the index of the letter of the final letter of "word" the users' input
#use this to "steal" a letter each time
#index is the length of the word - 1 to give a valid index number
index = len(word) - 1

#steals a letter until word is empty, adding each letter to "reverse" each time (in reverse)
while word:
    reverse += word[index]
    word = word[:index]
    print(reverse)

print(reverse)
input("press enter to exit")

致力于制作一个简单的程序,将用户输入的单词反向拼写并通过“窃取”原始字母并从中创建新字符串来将其打印回给用户。 我遇到的麻烦是这段代码在 反向 += 单词[索引] 获得相同结果的帮助或更好的方法非常感谢。

【问题讨论】:

  • reverse +=... 行之前放置一个print(index, len(word)) 行,看看会发生什么。

标签: python string indexing range


【解决方案1】:

在python中反转一个单词比这更简单:

reversed = forward[::-1]

我不会使用循环,它更长且可读性差。

【讨论】:

  • Python 字符串没有pop 函数。
  • 多么尴尬,我总是把字符串当作列表。已修复,谢谢!
【解决方案2】:

虽然其他人已经指出了在 Python 中反转单词的多种方法,但我认为这是您的代码存在的问题。

index 始终保持不变。假设用户输入了一个四个字母的单词,例如abcd。索引将设置为三个 (index = len(word) - 1)。然后在循环的第一次迭代期间,word 将减少为 abc (word = word[:index])。然后,在循环的下一次迭代中,在其中的第一行 (reverse += word[index]) 您将收到错误消息。 index 还是三个,所以你尝试访问index[3]。但是,由于word 已被缩短,因此不再有index[3]。您需要在每次迭代中将index 减少一个:

while word:
    reverse += word[index]
    word = word[:index]
    index -= 1

这是在 Python 中反转单词的另一种方法(不过,Wills 代码是最简洁的):

reverse = "".join([word[i-1] for i in range(len(word), 0, -1)])

编码愉快!

【讨论】:

    【解决方案3】:

    你会想要使用"range" 函数。

    range(start, stop, step)
    

    返回一个从开始到停止逐步增加(或减少)的列表。然后你可以遍历列表。总之,它看起来像这样:

    for i in range(len(word) -1, -1, -1):
        reverse += word[i]
        print(reverse)
    

    或者更简单的方法是使用string slicing 直接反转单词,然后遍历它。像这样:

    for letter in word[::-1]:
        reverse += letter
        print(reverse)
    

    按照现在的写法,它不仅会向后打印单词,而且还会打印向后单词的每个部分。例如,如果用户输入“Hello”,它将打印

    o
    ol
    oll
    olle
    olleH
    

    如果你只是想把单词倒着打印,最好的办法就是

    print(word[::-1])
    

    【讨论】:

      【解决方案4】:

      这是因为你没有改变index的值

      修改:

      while word:
          reverse += word[index]
          word = word[:index]
          index-=1
      print(reverse)`
      

      也就是说,每次循环获取word的当前最后一个字母时,您都必须减少索引

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        相关资源
        最近更新 更多