I am trying to get the first capital letter in the string but I am getting an index out of range error
I don't know if it is my base case for the recursion. Please can someone help me
This is my code:
def firstCapital(str, i):
if (str[i] == None):
return 0
if (str[i].isupper()):
return str[i]
return firstCapital(str, i + 1)
name = "geoRge"
res = firstCapital(name, 0)
if (res == 0):
print("No uppercase letter")
else:
print(res)
str[i]
will raise this index out of range
exception if i
is greater or equal to the length of str
. You should change your base case to:
if (i >= len(str)):
return 0
The line if (str[i] == None):
doesn't do what you want it to do. This seems like it's trying to check if your index is off the end of the string, but strings in Python don't have None
after the last real character. Rather, you get exactly the exception you describe when you try to index past the end.
Instead, you should be comparing i
to len(str)
, which is the length of the string as a number. Since indexes start at zero, an index equal to len(str)
is just past the end, so you probably want:
if i >= len(str):
return 0
I'd also double check if returning zero is what you want to do there. If you find a capital letter, you're returning it from your other conditional case. It's not always ideal to return different types in different situations, as it can be tricky for the caller to know what APIs they can use on the result. Returning an empty string, or None
might make more sense than returning a number.
using str[i]==None will 'force' python to determine the value of str[i], which doesn't exist, thus the index out of range error. You can determine that you reached the end of the string using len(str) and i instead:
def firstCapital(str, i):
if i>len(str)-1: #Instead of str[i]==None
return 0
if str[i].isupper():
return str[i]
return firstCapital(str, i + 1)
input : ('Ali',0)
Output: 'A'
Input: ('lia',0)
Output:0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.