thangvc91
thangvc91

Reputation: 333

Python - Using recursive to replace string in python

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

Upvotes: 0

Views: 307

Answers (2)

nikeros
nikeros

Reputation: 3379

You else does not return anything You could write 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 

Even if I would not recommended in the specific case, you could achieve similar results without using return running something like this:

def remove_text(to_remove):
    global input_str
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx > -1:
        input_str = input_str[:max(0, idx - 1)] + input_str[idx + len2: ]
        remove_text(to_remove)
    
input_str = "Hello my name is XXX Hello 12345 6 "
remove_text("Hello")
print(input_str)

In this case, remove_text will work recursively on the global input_str defined outside its natural scope: practically, you would need to have input_str defined outside the function before calling it.

Upvotes: 0

dabdya
dabdya

Reputation: 88

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

Upvotes: 1

Related Questions