oaklander114
oaklander114

Reputation: 3383

Replace substrings with elements of a list of tuples

I have a string as such:

string = """
 foobar_tent\n
 missyamica_ole
 """

this is a list of tuples I have:

 t = [("foo","virtue"), ("ole, "allo")]

I'm trying to replace every instance of the first element of each tuple with the second element of each tuple. So the result would be this:

newstring = """
 virtuebar_tent
 missyamica_allo
 """"

I tried doing it as such, but it doesn't alter anything.

newstring = ""
for a,b in t:
     newstring = string.replace(a,b)

Upvotes: 0

Views: 47

Answers (2)

Aidan Kane
Aidan Kane

Reputation: 4006

You were basically right. Main issue is that you were doing string.replace each time so only the last of your replacements in the list would have worked.

newstring = string
for a,b in t:
    newstring = newstring.replace(a,b)

Upvotes: 1

falsetru
falsetru

Reputation: 369294

newstring is overwritten in the loop by replaced original string.

Use newstring.replace instead of string.replace, so that the replaced string is not to be overwritten.

>>> string = """
... foobar_tent
... missyamica_ole
... """
>>> t = [("foo", "virtue"), ("ole", "allo")]
>>>
>>> newstring = string  # <-----
>>> for a,b in t:
...     newstring = newstring.replace(a,b) # <----
...
>>> newstring
'\nvirtuebar_tent\nmissyamica_allo\n'
>>> print(newstring)

virtuebar_tent
missyamica_allo

Upvotes: 1

Related Questions