这是我的代码:
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/