I have written a recursive to filter the string , but the output isn't my expected, could you please help assist this ?
s2 = "Hello"
def remove_text(s):
t = s.find(s2)
t2 = len(s2)
if t == -1:
return s
else:
if t == 0:
s = s[t2 1:]
else:
s = s[0:t-1] s[t len(s2):]
if s.find(s2) >= 0: #if still found s2 in s
remove_text(s)
s1 = "Hello my name is XXX Hello 12345 6 "
s3 = remove_text(s1)
print(s3)
the output i got always is "None" . I expected the output is:
my name is XXX 12345 6
CodePudding user response:
s2 = "Hello"
def remove_text(s):
t = s.find(s2)
t2 = len(s2)
if t == -1:
return s
else:
if t == 0:
s = s[t2 1:]
else:
s = s[0:t-1] s[t len(s2):]
if s.find(s2) >= 0: #if still found s2 in s
s = remove_text(s)
return s
s1 = "Hello my name is XXX Hello 12345 6 "
s3 = remove_text(s1)
print(s3)
You forgot to write return. It is not enough to add return only at the end, so it is better to assign the result of a recursive call to the string s, and then return s
CodePudding user response:
You else does not return anything
You could write more in a more compact way as follows:
def remove_text(input_str, to_remove):
idx, len2 = input_str.find(to_remove), len(to_remove)
if idx == -1:
return input_str
else:
return remove_text(input_str[:max(0, idx - 1)] input_str[idx len2:], to_remove)
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")
print(result)
OUTPUT
my name is XXX 12345 6
