Skip to main content
 首页 » 编程设计

python之使用递归在python中获取子字符串

2025年05月04日22飞鱼

我如何使用递归来查找字符串中“a”的数量:

例子: get_a('你好') -> 2

这是我的:

    def get_a(string): 
        ''' 
        return how many times a exist in the string using recursion 
        ''' 
        if string == '': 
            return 0 
        if string[0] == 'a': 
            return 1 
    return get_a(string[1:]) 

请您参考如下方法:

您的代码中的问题是当您找到第一个a 时就停止了递归。您需要调用 get_a 并收集您已经找到的 a:

def get_a(string): 
    ''' 
    return how many times a exist in the string using recursion 
    ''' 
    if string == '': 
        return 0 
    if string[0] == 'a': 
        return 1 + get_a(string[1:]) 
    return get_a(string[1:])