How to strip a specific word from a string?

后端 未结 5 1100
醉话见心
醉话见心 2020-12-03 04:20

I need to strip a specific word from a string.

But I find python strip method seems can\'t recognize an ordered word. The just strip off any characters passed to the

5条回答
  •  不思量自难忘°
    2020-12-03 04:56

    Use str.replace.

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

    Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.

    >>> 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'
    

提交回复
热议问题