Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - Weird function return value?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...