替代Python字符串替换方法

时间:2011-12-04 04:57:28

标签: python string

我想从段落中删除某些单词,例如“and”,“as”和“like”。是否有更简单的方法从字符串中删除单词而不是通过替换 -

new_str = str.replace(' and ', '').replace(' as ', '').replace(' like ', '')

例如,是否有类似以下的方法?

str.remove([' and ', ' like ', ' as '])

4 个答案:

答案 0 :(得分:8)

是的,您可以使用sub模块中的re功能:

>>> import re
>>> s = 'I like this as much as that'
>>> re.sub('and|as|like', '', s)
'I  this  much  that'

答案 1 :(得分:1)

您可以使用正则表达式:

    >>> import re
    >>> test = "I like many words but replace some occasionally"
    >>> to_substitute = "many|words|occasionally"
    >>> re.sub(to_substitute, '', test)
    'I like   but replace some '

答案 2 :(得分:1)

你也可以没有正则表达式。请参阅以下示例

def StringRemove(st,lst):
    return ' '.join(x for x in st.split(' ') if x not in lst)

>>> StringRemove("Python string Java is immutable, unlike C or C++ that would give you a performance benefit. So you can't change them in-place",['like', 'as', 'and'])
"Python string Java is immutable, unlike C or C++ that would give you a performance benefit. So you can't change them in-place"

>>> st="Python string Java is immutable,     unlike C or C++ that would  give you a performance benefit. So you can't change them in-place"
>>> StringRemove(st,['like', 'as', 'and'])==st
True
>>> 

答案 3 :(得分:1)

请注意,如果你关心的只是可读性而不是性能,你可以这样做:

new_str = str
for word_to_remove in [' and ', ' as ', ' like ']:
    new_str = new_str.replace(word_to_remove, '')