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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23669024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:18:20  来源:igfitidea点击:

How to strip a specific word from a string?

pythonstringstrip

提问by Zen

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.

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

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?

我怎么能用python去掉一个指定的词?

采纳答案by metatoaster

Use str.replace.

使用str.replace.

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

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

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

回答by iamdev

Easiest way would be to simply replace it with an empty string.

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

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

回答by Akshay Karapurkar

You can also use a regexp with re.sub:

您还可以使用正则表达式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)

回答by Michael Strobel

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

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

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

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

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

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