2015-10-04 77 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)