python - 什么是IndexError?我不断得到它

标签 python for-loop while-loop syntax-error python-3.3

这是我的代码:

quote = input("Enter a Sentence: ")

a = len(quote)
counter = 0
counter1 = 0
reverse = a

print("The Length of the sentence is",a,"characters long!")

for x in range(0,a):
    if str.isspace(quote[x]) == True:
        counter = counter + 1

print("The Length of the sentence is",a - counter,"characters long (excluding space...)!")

for x in range(0,a):
    if str.isupper(quote[x]) == True:
        counter1 = counter1 + 1

print("The number of Upper Case Characters in the sentence is",counter1,"characters!")

print("The number of Lower Case Characters in the sentence is",a-counter1,"characters long!\n")


while reverse >= 1:
    r = reverse
    print(quote[r])
    r = r - 1

目的是找到有关该句子的所有内容,但唯一的问题是底部的“While”循环。它似乎不起作用,目的是使句子“反”。但是,它给了我一个看起来像这样的错误:
Traceback (most recent call last):
  File "C:\Documents and Settings\ususer\My Documents\Downloads\StringStuff.py", line 27, in <module>
    print(quote[r])
IndexError: string index out of range

我究竟做错了什么?请帮忙!

最佳答案

Python的索引是0,因此字符串的第一个字符是str[0],最后一个字符是str[len(str) - 1]。因此,由于您以reverse = len(quote)开头,所以最后要执行quote[len(quote)],它比字符串末尾晚了一个。

因此,您可能应该以reverse = a - 1开头,最后的循环应类似于:

while reverse >= 0:
    print(quote[reverse])
    reverse = reverse - 1

关于python - 什么是IndexError?我不断得到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457864/

相关文章:

JavaScript 不将变量写为数字(循环)

c - 带有嵌套 for 循环的简单 C 程序在 Windows Powershell 中停止工作

带有 While 循环的 Javascript 贷款计算器

python - 使用 rauth 连接到 LinkedIn API

python - 为 Python Twisted SOAP 服务器自动生成 WSDL 文件

javascript - 从列表javascript向表添加行

java - 初学者循环问题 - while ... do

java while (LinkedList.iterator().hasNext()) 不起作用

Python 枚举 - 我看不到什么?

python - ImportError : No module named twisted. persisted.styles