Skip to main content
 首页 » 编程设计

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

2025年05月04日19傻小

在 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)