-1

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))

output:
None

sloth
  • 99,095
  • 21
  • 171
  • 219
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504

3 Answers3

3

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
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • 1
    To add, when function ends without the explicit `return` or with explicit `return` that is given no argument, then it is the same as if you used `return None`. – pepr Jun 19 '12 at 20:00
1
...
#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.

sloth
  • 99,095
  • 21
  • 171
  • 219
1

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)
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180