获取IndexError:python中的字符串索引超出范围

获取IndexError: python中的字符串索引超出范围,我是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.")


慕无忌1623718
浏览 192回答 3
3回答

FFIVE

尝试使用len(string)而不是 25 ,因为在这里您将遍历所有 25 个整数。但是在您的情况下,您的字符串中应该有 25 个字符并不是强制性的,它可以是 25 个或小于 25 个。因此,当它小于 25 个字符并且您尝试使用第 25 个字符时,它将显示错误:代替 :while&nbsp;i&nbsp;<&nbsp;25&nbsp;:尝试:while&nbsp;i&nbsp;<&nbsp;len(string)

翻阅古今

你也可以试试这个:string = input('Enter string upto 25 words: ')if len(string) > 25:&nbsp; &nbsp; print('Please enter a string less than 25 words.')else:&nbsp; &nbsp; total_lwr = sum(map(str.islower, string))&nbsp; &nbsp; total_upr = sum(map(str.isupper, string))你不需要为此使用 while,也不需要替换任何东西。更少的代码。:)

牧羊人nacy

的同时,应该如下图所示:while i < len(string):编码 :string = input('Enter string upto 25 words: ')if len(string) > 25:&nbsp; print('Please enter a string less than 25 words.')else:&nbsp; string.replace(" ", "")&nbsp; total_upr = 0&nbsp; total_lwr = 0&nbsp; i = 0&nbsp; while i < len(string):&nbsp; &nbsp; print(i)&nbsp; &nbsp; if string[i].islower():&nbsp; &nbsp; &nbsp; total_lwr += 1&nbsp; &nbsp; elif string[i].isupper():&nbsp; &nbsp; &nbsp; total_upr += 1&nbsp; &nbsp; i += 1&nbsp; print(f"'{string}' contains {total_lwr} lower-case letters and {total_upr} upper-case letters.")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python