简体   繁体   English

Python:字符串索引超出范围,试图找到第一个大写字母

[英]Python :string index out of range with trying to find first capital letter

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.我正在尝试获取字符串中的第一个大写字母,但出现index out of range error我不知道这是否是我的递归基本情况。 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 .如果i大于或等于str的长度, str str[i]将引发此index out of range异常。 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.if (str[i] == None):不做你想做的事。 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.这似乎是在尝试检查您的索引是否在字符串的末尾,但是 Python 中的字符串在最后一个真实字符之后没有None 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.相反,您应该将ilen(str)进行比较,后者是作为数字的字符串长度。 Since indexes start at zero, an index equal to len(str) is just past the end, so you probably want:由于索引从零开始,等于len(str)的索引刚好在末尾,因此您可能需要:

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.在不同情况下返回不同类型并不总是理想的,因为调用者很难知道他们可以对结果使用哪些 API。 Returning an empty string, or None might make more sense than returning a number.返回一个空字符串或None可能比返回一个数字更有意义。

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.使用 str[i]==None 将“强制”python 确定不存在的 str[i] 的值,因此索引超出范围错误。 You can determine that you reached the end of the string using len(str) and i instead:您可以使用 len(str) 和 i 来确定您到达了字符串的末尾:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM