-1

I want to do the following:

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

The output then should be hleeo wored, but it seems like I am not allowed to use replace with an array as input. Is there a way to still do it like this?

  • 1
    With a dictionary? `dict(zip(A, B))` and then do the replacement – roganjosh Mar 08 '20 at 22:24
  • 3
    Does this answer your question? [How to replace multiple substrings of a string?](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) – mlg556 Mar 08 '20 at 22:29

2 Answers2

1

This will work:

newthing = thing
for a,b in zip(A, B):
    newthing = newthing.replace(a, b)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Gianluca
  • 536
  • 4
  • 7
  • This is a nice and clean approach, but sadly will not give the desired output (because of the cyclic `e -> l`, `l -> e`) – Tomerikoo Mar 08 '20 at 22:33
  • This is what I thought too, but it doesn't aim for his desired output which is "hleeo wored" – 010011100101 Mar 08 '20 at 22:33
  • As was pointed out, this solution has a problem that it also replaces the strings which have already been replaced, but this is not a problem for my actual code so I will accept the answer. – Ruben Lier Mar 08 '20 at 22:50
0

Here's what I came up with.

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
010011100101
  • 1,630
  • 1
  • 10
  • 20
  • 1
    hm ... but this works only with 1-letter replacements, isn't it? – Gwang-Jin Kim Mar 08 '20 at 22:46
  • It also might be better to transform `a` and `b` to a mapping by `dict(zip(a, b))` so you can save on that search-&-replace to a mere `_thing += mapping.get(s, s)` – Tomerikoo Mar 09 '20 at 07:49