如何从字符串中删除特定单词? [英] How to strip a specific word from a string?

查看:100
本文介绍了如何从字符串中删除特定单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串中去除特定的单词.

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

例如:

<预><代码>>>>papa = "爸爸是个好人">>>app = "app 很重要">>>papa.lstrip('爸爸')是个好人">>>app.lstrip('爸爸')很重要"

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

解决方案

使用 str.replace.

<预><代码>>>>papa.replace('爸爸', '')'是个好人'>>>app.replace('爸爸', '')'应用很重要'

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

<预><代码>>>>进口重新>>>papa = '爸爸是个好人'>>>app = 'app 很重要'>>>papa3 = '爸爸是爸爸,爸爸'>>>>>>patt = re.compile('(\s*)papa(\s*)')>>>patt.sub('\\1mama\\2', papa)'妈妈是个好人'>>>patt.sub('\\1mama\\2', papa3)'妈妈是妈妈,妈妈'>>>patt.sub('', papa3)'是一个,并且'

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

For example:

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

How could I strip a specified word with python?

解决方案

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'

这篇关于如何从字符串中删除特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆