2015-10-04 83 views
-1

我triying从列表中删除,包含“@”从字符串中删除词与

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) 

所有单词,并返回:

@test2 @test4 a comment 

我想删除所有的话包含'@'不只是第一个,我该怎么做? 谢谢

+0

你想从列表中删除,或做你想从字符串中删除? – juanchopanza

+0

我收到一个字符串,所以..从列表 – Darcyys

+0

这绝对没有意义。 – juanchopanza

回答

1

当您迭代它时,不要从列表中删除值。

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 
+0

非常感谢,它的工作原理! – Darcyys

0

正则表达式模块有这样做的直接的方法:

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

要打破正则表达式:

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)