String 使用递归将一个子字符串的所有出现替换为另一个子字符串

String 使用递归将一个子字符串的所有出现替换为另一个子字符串,string,recursion,python-3.x,substring,String,Recursion,Python 3.x,Substring,给定一个字符串及其两个子字符串(命名为a和b),我需要编写一个递归函数,用a替换所有出现的b,然后返回新字符串 有人能帮我如何开始吗?您知道您的函数应用于: 基本大小写)一个空字符串,必须返回一个空字符串 rec case)以b开头的字符串必须用A替换b,并检查字符串的其余部分 rec case)否则,返回链接到递归返回的字符串其余部分的字符串的第一个字符 以下是算法: def rec_replace(string, a, b): if not string: #if the str

给定一个字符串及其两个子字符串(命名为a和b),我需要编写一个递归函数,用a替换所有出现的b,然后返回新字符串


有人能帮我如何开始吗?

您知道您的函数应用于:

  • 基本大小写)一个空字符串,必须返回一个空字符串
  • rec case)以
    b
    开头的字符串必须用
    A
    替换
    b
    ,并检查字符串的其余部分
  • rec case)否则,返回链接到递归返回的字符串其余部分的字符串的第一个字符
以下是算法:

def rec_replace(string, a, b):
    if not string: #if the string is empty
        return ""
    elif string[:len(b)] == b: #if the string start with b, replace it with a
        return a + rec_replace(string[len(b):], a, b)
    else: #else, add this character and go to the next one
        return string[0] + rec_replace(string[1:], a, b)
测试:

输出:

ok this is ok a simple ok test

递归地,您知道您的函数应用于:

  • 基本大小写)一个空字符串,必须返回一个空字符串
  • rec case)以
    b
    开头的字符串必须用
    A
    替换
    b
    ,并检查字符串的其余部分
  • rec case)否则,返回链接到递归返回的字符串其余部分的字符串的第一个字符
以下是算法:

def rec_replace(string, a, b):
    if not string: #if the string is empty
        return ""
    elif string[:len(b)] == b: #if the string start with b, replace it with a
        return a + rec_replace(string[len(b):], a, b)
    else: #else, add this character and go to the next one
        return string[0] + rec_replace(string[1:], a, b)
测试:

输出:

ok this is ok a simple ok test

什么意义上的递归?什么意义上的递归?