![](/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.