简体   繁体   English

Python - 使用递归替换 python 中的字符串

[英]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?我写了一个递归来过滤字符串,但是 output 不是我的预期,你能帮忙吗?

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".我得到的 output 总是“无”。 I expected the output is:我预计 output 是:

my name is XXX 12345 6
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.你忘了写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只在最后加上return是不够的,最好把递归调用的结果赋给字符串s,然后return s

You else does not return anything You could write in a more compact way as follows: else您不会返回任何内容您可以以更紧凑的方式编写如下:

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 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:即使我在特定情况下不推荐,您也可以在不使用return运行的情况下获得类似的结果:

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.在这种情况下, remove_text将递归地在其自然 scope 之外定义的全局input_str上工作:实际上,在调用它之前,您需要在input_str之外定义 input_str。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM