hhppaarr
hhppaarr

Reputation: 49

Replacing several strings in a list in a single statement

I am trying to replace the third and forth words of this list by two different words in one single statement and just can't seem to find of doing it what I tried doesn't work with the error AttributeError: 'list' object has no attribute 'replace':

friends = ["Lola", "Loic", "Rene", "Will", "Seb"]
friends.replace("Rene", "Jack").replace("Will", "Morris")

Upvotes: 0

Views: 192

Answers (3)

fountainhead
fountainhead

Reputation: 3722

This is a not so pretty solution, but a one-liner nevertheless:

friends = list(map(lambda x: x if x != "Will" else "Morris", map(lambda x: x if x != "Rene" else "Jack", friends)))

Brief explanation:

It's a "map(lambda, list)" solution, whose output list is passed as input list to another outer "map(lambda, list)" solution.

The lambda in the inner map is for replacing "Will" with "Morris".

The lambda in the outer map is for replacing "Rene" with "Jack"

Upvotes: 0

pault
pault

Reputation: 43494

Another way, if you don't mind the overhead of converting the list to a pandas.Series:

import pandas as pd

friends = ["Lola", "Loic", "Rene", "Will", "Seb"]

friends = pd.Series(friends).replace(to_replace={"Rene":"Jack", "Will":"Morris"}).tolist()
print(friends)
#['Lola', 'Loic', 'Jack', 'Morris', 'Seb']

Upvotes: 1

Robin Zigmond
Robin Zigmond

Reputation: 18249

If you want to do multiple replacements probably the easiest way is to make a dictionary of what you want to replace with what:

replacements = {"Rene": "Jack", "Will": "Morris"}

and then use a list comprehension:

friends = [replacements[friend] if friend in replacements else friend for friend in friends]

Or more compactly, using dict.get() with a default value.

friends = [replacements.get(friend, friend) for friend in friends]

Upvotes: 8

Related Questions