0

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?

2
  • 1
    What is your desired output? Commented Dec 21, 2017 at 18:23
  • 1
    @Ajax1234 I'd think ['@user', 'nina', 'michael', '@user'] Commented Dec 21, 2017 at 18:24

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

That's not valid syntax in Python. See other answers for correct solution.
2

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]

Comments

1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.