如何从字符串中删除特定单词?

时间:2014-05-15 03:59:01

标签: python string strip

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

但我发现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剥离指定的单词?

7 个答案:

答案 0 :(得分:38)

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:2)

您还可以使用带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)

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

执行此操作的一种“懒惰”方法是使用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'

答案 5 :(得分:0)

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

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

检查一下:

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