![](/img/trans.png)
[英](python) I keep getting an IndexError: string index out of range
[英]Getting IndexError: string index out of range in 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.")
尝试使用len(string)
而不是25,因为这里要遍历所有25个整数。 但是在您的情况下,您的字符串中必须刚好有25个字符(可以是25个或少于25个字符)不是强制性的。因此,当字符串少于25个字符并且您尝试采用第25个字符时,它将显示错误:
代替 :
while i < 25 :
尝试:
while i < len(string)
您也可以尝试以下操作:
string = input('Enter string upto 25 words: ')
if len(string) > 25:
print('Please enter a string less than 25 words.')
else:
total_lwr = sum(map(str.islower, string))
total_upr = sum(map(str.isupper, string))
您无需为此而使用,也无需更换任何东西。 更少的代码。 :)
时间应如下所示:
while i < len(string):
编码 :
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 < len(string):
print(i)
if string[i].islower():
total_lwr += 1
elif string[i].isupper():
total_upr += 1
i += 1
print(f"'{string}' contains {total_lwr} lower-case letters and {total_upr} upper-case letters.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.