-1

I am triying to remove from a list, all words that contains "@"

string = "@THISISREMOVED @test2 @test3 @test4 a comment"
splitted = string.split()

for x in splitted:
    if '@' in x:
        splitted.remove(x)

string =' '.join(splitted)
print(string)

And it returns:

@test2 @test4 a comment

I want to delete ALL words that contains '@' not just the first one, how i can do that? Thanks

Darcyys
  • 149
  • 2
  • 12

2 Answers2

1

Don't remove values from list while you are iterating over it.

string = "@THISISREMOVED @test2 @test3 @test4 a comment"
splitted = string.split()

result = []

for x in splitted:
    if '@' not in x:
        result.append(x)



string =' '.join(result)
print(string)

>>> a comment
xiº
  • 4,605
  • 3
  • 28
  • 39
0

The regular expression module has a direct way of doing this:

>>> import re
>>> r = re.compile('\w*@\w*')
>>> r.sub('',  "@THISISREMOVED @test2 @test3 @test4 a comment")
'    a comment'

To break down the regular expression:

r = re.compile('''
               \w* # zero or more characters: a-z, A-Z, 0-9, and _
               @   # an @ character
               \w* # zero or more characters: a-z, A-Z, 0-9, and _
               ''',
               re.VERBOSE)
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331