gpt4 book ai didi

python - 获取 IndexError : string index out of range in python

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:37 24 4
gpt4 key购买 nike

在 python 中出现 IndexError: string index out of range,我是 python 的初学者,我试图制作一个程序来计算大写和小写字母的总数,我也尝试了一些解决方案将字符串的空格删除为 string.replace("", "") 但再次出现错误,

我的代码

string = input('Enter string upto 25 words: ')
if len(string) > 25:
print('Please enter a string less than 25 words.')
else:
string.replace(" ", "")
total_upr = 0
total_lwr = 0
i = 0
while i < 25:
print(i)
if string[i].islower():
total_upr += 1
elif string[i].isupper():
total_lwr += 1
i += 1
print(f"'{string}' contains {total_lwr} lower-case letters and {total_upr} upper-case letters.")

最佳答案

尝试使用 len(string) 而不是 25 ,因为在这里您要遍历所有 25 个整数。但在你的情况下,你的字符串中不应该有 25 个字符,它可以是 25 个或小于 25 个。所以当它小于 25 个字符并且你试图取第 25 个字符时,它会显示错误:

代替:

while i < 25 :

尝试:

while i < len(string)

关于python - 获取 IndexError : string index out of range in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53928698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com