【问题标题】:How to strip a specific word from a string?如何从字符串中删除特定单词?
【发布时间】:2014-07-03 08:33:50
【问题描述】:

我需要从字符串中删除一个特定的单词。

但我发现 python strip 方法似乎无法识别有序单词。只是去掉传递给参数的所有字符。

例如:

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.lstrip('papa')
" is a good man"
>>> app.lstrip('papa')
" is important"

如何用 python 去掉指定的单词?

【问题讨论】:

  • 你看S.lstrip的文档了吗?它所做的事情与你想做的事情完全不同。你想replace这个字符串什么都没有。
  • 你想让“木瓜”这个词发生什么?
  • @DSM 我猜输出应该是ya。让我们等待OP确认
  • @zen 你确定接受的答案没问题吗?试试这个print "papa is papa is papa".replace('papa', ''),如果你的输出没问题,那么接受的答案是正确的。
  • 只是想添加一些东西。请注意,如果您试图删除句子中的最后一个单词,那么您将在句子末尾留下一个空格,这可能是不希望的。例如,如果你做了papa.replace('man', '')。你最终会得到'papa is a good '(注意'good'后面的空格。

标签: python string strip


【解决方案1】:

使用str.replace

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

或者使用re 并使用正则表达式。这将允许删除前导/尾随空格。

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

【讨论】:

  • 试试print "papa is papa is papa".replace('papa', '')
  • 分心了,没有完成使用 re 的示例,这将允许删除前导/尾随空格。
  • @thefourtheye 它返回'是'。所有三个“爸爸”都根据实际需要被删除。我可以知道你应该从你的观点推断什么吗?
  • @metatoaster "papa.replace('papa', '').strip()" 还会删除前导和尾随空格。
【解决方案2】:

最简单的方法是用空字符串替换它。

s = s.replace('papa', '')

【讨论】:

  • 您可能还想在 papa 之后添加一个空格 - 我假设他不希望在字符串中留下前导空格。
  • 试试print "papa is papa is papa".replace('papa', '')
  • @JacobKudria "s = s.replace('papa', '').strip()" 也可以达到目的。
【解决方案3】:

您也可以使用带有re.sub 的正则表达式:

article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

【讨论】:

    【解决方案4】:

    如果您知道要在字符数组中替换的每个单词的开头和结尾的索引值,并且您只想替换该特定数据块,则可以这样做。

    >>> s = "papa is papa is papa"
    >>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
    >>> print(s)
    papa is mama is papa
    

    或者,如果您还希望保留原始数据结构,可以将其存储在字典中。

    >>> bin = {}
    >>> s = "papa is papa is papa"
    >>> bin["0"] = s
    >>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
    >>> print(bin["0"])
    papa is papa is papa
    >>> print(s)
    papa is mama is papa
    

    【讨论】:

      【解决方案5】:

      如果想从只删除字符串的开头中的单词,那么你可以这样做:

        string[string.startswith(prefix) and len(prefix):]  
      

      其中 string 是您的字符串变量,prefix 是您要从字符串变量中删除的前缀。

      例如:

        >>> papa = "papa is a good man. papa is the best."  
        >>> prefix = 'papa'
        >>> papa[papa.startswith(prefix) and len(prefix):]
        ' is a good man. papa is the best.'
      

      【讨论】:

        【解决方案6】:

        有点“懒惰”的方法是使用startswith——它更容易理解,而不是正则表达式。然而,正则表达式可能会更快,我没有测量。

        >>> papa = "papa is a good man"
        >>> app = "app is important"
        >>> strip_word = 'papa'
        >>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
        ' is a good man'
        >>> app[len(strip_word):] if app.startswith(strip_word) else app
        'app is important'
        

        【讨论】:

          【解决方案7】:

          检查一下:

          use replace()
          ------------
          var.replace("word for replace"," ")
          -----------------------------------
          one = " papa is a good man"
          
          two = " app is important"
          
          one.replace(" papa ", " ")
          
          output=> " is a good man"
          
          two.replace(" app ", " ")
          
          output=> " is important
          

          【讨论】:

            【解决方案8】:

            如果我们谈论的是前缀和后缀,并且您的 Python 版本至少为 3.9,那么您可以使用这些new methods

            >>> 'TestHook'.removeprefix('Test')
            'Hook'
            >>> 'BaseTestCase'.removeprefix('Test')
            'BaseTestCase'
            
            >>> 'MiscTests'.removesuffix('Tests')
            'Misc'
            >>> 'TmpDirMixin'.removesuffix('Tests')
            'TmpDirMixin'
            

            【讨论】:

              猜你喜欢
              • 2014-02-26
              • 2021-12-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多