使用递归来获取python中的子字符串

Har*_*bim 1 python string recursion substring python-3.x

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

例如:get_a('halloa') - > 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:])
Run Code Online (Sandbox Code Playgroud)

And*_*eyF 6

你的代码中的问题是你找到第一个时停止递归a.你想要打电话get_a并收集a你已经发现的s:

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:])
Run Code Online (Sandbox Code Playgroud)