奇怪的函数返回值? [英] Weird function return value?

查看:52
本文介绍了奇怪的函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除字符串中大括号之间的所有内容,并尝试递归地执行此操作.当递归结束时,我将在这里返回 x,但不知何故,函数 doit 在这里返回 None.尽管在 def 中打印 x 会打印正确的字符串.我做错了什么?

I am trying to remove everything between curly braces in a string, and trying to do that recursivesly. And I am returning x here when the recursion is over, but somehow the function doit is returning None here. Though printing x within the def prints the correct string. What am I doing wrong?

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 块中,只有在其他所有内容都没有时才会执行.您想返回从递归中获得的值.

You never return anything if the if block succeeds. The return statement lies in the else block, and is only executed if everything else isn't. You want to return the value you get from the recursion.

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

这篇关于奇怪的函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆