Python 奇怪的函数返回值?

Python 奇怪的函数返回值?,python,python-3.x,return-value,Python,Python 3.x,Return Value,我正在尝试删除字符串中花括号之间的所有内容,并尝试递归地这样做。 当递归结束时,我在这里返回x,但不知怎的,函数doit在这里不返回任何值。尽管在def中打印x会打印正确的字符串。 我做错了什么 strs = "i am a string but i've some {text in brackets} braces, and here are some more {i am the second one} braces" def doit(x,ind=0): if x.find('{',

我正在尝试删除字符串中花括号之间的所有内容,并尝试递归地这样做。 当递归结束时,我在这里返回x,但不知怎的,函数doit在这里不返回任何值。尽管在def中打印x会打印正确的字符串。 我做错了什么

strs = "i am a string but i've some {text in brackets} braces, and here are some more {i am the second one} braces"
def doit(x,ind=0):
   if x.find('{',ind)!=-1 and x.find('}',ind)!=-1:
     start=x.find('{',ind)
     end=x.find('}',ind)
     y=x[start:end+1]
     x=x[:start]+x[end+1:]
     #print(x)
     doit(x,end+1)
   else:
       return x

print(doit(strs))
输出:

如果if块成功,则不会返回任何内容。return语句位于else块中,仅当其他语句都不存在时才执行。您希望返回从递归中获得的值

if x.find('{', ind) != -1 and x.find('}', ind) != -1:
    ...
    return doit(x, end+1)
else:
    return x
应该是

...
#print(x)
return doit(x,end+1)
...

if块中缺少return语句。如果函数本身是递归调用的,则它不会返回该调用的返回值。

请注意,使用正则表达式更容易:

import re
strs = "i am a string but i've some {text in brackets} braces, and here are some more {i am the second one} braces"
strs = re.sub(r'{.*?}', '', strs)

我注意到这是一种非常糟糕的方法,但我认为这是一种编程练习,因为我试图递归地执行语句。@Lattyware是的!我试图通过这一点解决一个SO问题。我知道这可以在一行中完成,我只是尝试了与使用regex不同的草书方法。要补充的是,当函数结束时没有显式返回或显式返回没有给出任何参数,则与使用无返回相同。
import re
strs = "i am a string but i've some {text in brackets} braces, and here are some more {i am the second one} braces"
strs = re.sub(r'{.*?}', '', strs)