用for删除字符串中的单词

时间:2015-10-04 13:27:28

标签: python loops

我正在试图从列表中删除包含" @"

的所有单词
#!/bin/sh

for i in -1 4.5
do  for j in 0 -2.2
    do  # -- keeps the highly portable printf utility from 
        # interpreting '-' as an argument 
        printf -- "$i" "$j\n" 
    done
done

它返回:

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)

我想删除包含' @'的所有字词。不只是第一个,我怎么能这样做? 感谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)
相关问题