Clement Attlee
Clement Attlee

Reputation: 733

Replace the whole string in a list of strings

I have a list of tokens. Some start with an @ sign. I want to change all those strings to a generic @user. I have tried this:

>>> words = ['@john', 'nina', 'michael', '@bebeto']
>>> words = [w.replace(w, '@user') for w in words if w.startswith('@')]
>>> words
['@user', '@user']
>>> 

What am I getting wrong here?

Upvotes: 0

Views: 658

Answers (3)

bphi
bphi

Reputation: 3185

Your list comprehension is causing the undesired output, just change

[w.replace(w, '@user') for w in words if w.startswith('@')]

To

[w.replace(w, '@user') if w.startswith('@') else w for w in words]

Upvotes: 3

jbch
jbch

Reputation: 186

First of all you can simplify the first part of the list comprehension. This is equivalent and doesn't do a needless replacement:

words = ['@user' for w in words if w.startswith('@')]

In a list comprehension, the if clause at the end decides what is included or not. So the if basically says, only keep elements which starts with '@'. But you want to keep all elements.

Instead you can use a conditional expression to decide whether to get '@user' or the original word:

words = ['@user' if w.startswith('@') else w for w in words]

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

words = ['@john', 'nina', 'michael', '@bebeto']
new_words = ['@user' if i.startswith('@') else i for i in words]

Output:

['@user', 'nina', 'michael', '@user']

Upvotes: 1

Related Questions