【问题标题】:Remove word from string start with specific characters从字符串中删除以特定字符开头的单词
【发布时间】:2018-12-22 22:39:55
【问题描述】:

我有以下字符串:

my_string = "This is an example string, ex , excatly , index , hyperextension"

我想删除 Python 中所有以ex 开头的单词。

所以我想要的结果是:

remove_words_that_start_with_ex("my_string")
print(my_string)

想要的结果:

这是一个字符串, , , index , 超扩展

我试着做这样的事情:

main_str = " ".join(filter(lambda x:x[0,1]!='ex', main_str.split()))

但它只适用于一个字符,而不是 2 个(“ex”)。

【问题讨论】:

  • 使用x[:2] 代替x[0,1],或x.startswith('ex')

标签: python string python-2.7 split


【解决方案1】:

你可以像这样使用python内置的startswith方法:

>>> my_string = "This is an example string, ex , excatly , index , hyperextension"
>>>
>>> print ' '.join(x for x in my_string.split() if not x.startswith('ex'))
This is an string, , , index , hyperextension

现在,如果您只想修复 lambda,这里有一个修复方法:

>>> print " ".join(filter(lambda x: x[0:2]!='ex', my_string.split()))
This is an string, , , index , hyperextension

【讨论】:

    【解决方案2】:

    您可以使用re.sub 来执行此操作

    >>> import re
    >>> my_string = "This is an example string, ex , excatly , index , hyperextension"
    >>> re.sub('(?:\s)ex[^, ]*', '', my_string)
    'This is an string, , , index , hyperextension'
    

    【讨论】:

      【解决方案3】:

      你可以使用re.sub:

      import re
      my_string = "This is an example string, ex , excatly , index , hyperextension"
      final_string = re.sub('(?<=\s)ex[\w]+|(?<=^)ex[\w]+', '', my_string)
      

      输出:

      'This is an  string, ex ,  , index , hyperextension'
      

      或者,通过提供lambda

      final_string = re.sub('\w+', lambda x:'' if x.group().startswith('ex') else x.group(), my_string)
      

      输出:

      'This is an  string,  ,  , index , hyperextension'
      

      【讨论】:

      • 嗨,我没有投反对票(如果我这样做了,我会解释原因)但只是注意到您使用re 的第一个sn-p 保留了ex应该删除的词。 lambda 工作正常!
      • 另外,如果你想使用re.sub,你可以改变正则表达式,例如到(?&lt;=\s)ex[\w]*[\s*]
      最近更新 更多