使用替换字符串数组

时间:2020-03-08 22:21:18

标签: python str-replace

我要执行以下操作:

thing = "hello world"
A = ["e","l"]
B = ["l","e"]
newthing = thing.replace(A,B)
print(newthing)

然后应该很高兴地输出了输出,但是似乎不允许使用数组替换作为输入。有办法仍可以像这样吗?

2 个答案:

答案 0 :(得分:1)

这将起作用:

newthing = thing
for a,b in zip(A, B):
    newthing = newthing.replace(a, b)

答案 1 :(得分:0)

这就是我的想法。

thing = "hello world"
A = ["e","l"]
B = ["l","e"]

def replace_test(text, a, b):
    _thing = ''
    for s in text:
        if s in a:
            for i, val in enumerate(a):
                if s == val:
                    s = b[i]
                    break
        _thing += s
    return _thing

newthing = replace_test(thing, A, B) 
print(newthing)

#>> hleeo wored
相关问题