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

标签 python string python-3.x recursion substring

我如何使用递归来查找字符串中“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:])

关于python - 使用递归在python中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48688763/

相关文章:

python - 如何将 SQL 数据框中列的单个 MIN 值作为标量返回?

c++ - 返回最短的字符串

python - 在 Python 3 中打印 kwargs

python - pytest-模拟 pathlib.Path.open

python - 终端集中程序的输出到字符串?

python - django 中的动态数据库表

java - StreamTokenizer 将 001_to_003 拆分为两个 token ;我怎样才能阻止它这样做?

c - 将字符串扫描成结构

Python 文件-IO 和 zipfile。尝试循环遍历文件夹中的所有文件,然后使用Python循环遍历各个文件中的文本

python - vtk cubeAxesActor 中的轴限制和标签