Weird function return value?

前端 未结 3 1048
南旧
南旧 2020-12-12 07:47

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

相关标签:
3条回答
  • 2020-12-12 08:20

    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
    
    0 讨论(0)
  • 2020-12-12 08:24

    Note that it is easier to use regular expressions:

    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)
    
    0 讨论(0)
  • 2020-12-12 08:35
    ...
    #print(x)
    doit(x,end+1)
    ...
    

    should be

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

    You are missing the return statement in the if block. If the function is calls itself recursively, it doesn't return the return value of that call.

    0 讨论(0)
提交回复
热议问题