[英]How can I delete specific words or string from a python string without trimming it from other words in Python?
I would like to know how to remove specific words from a string in python without deleting them from other words they composed. 我想知道如何从python中的字符串中删除特定单词,而又不从它们组成的其他单词中删除它们。
For example if I want to remove 'is' from the following sentence: 例如,如果我想从以下句子中删除“是”:
s = 'isabelle is in Paris'
The .replace() function delete 'is' in 'isabelle' and in 'Paris': .replace()函数删除'isabelle'和'Paris'中的'is':
s = 'isabelle is in Paris'
s.replace('is', '')
It gives me abelle in Par
But I want isabelle in Paris
. 它让我
abelle in Par
同abelle in Par
但我想要isabelle in Paris
abelle in Par
。 Is there a way to delete only 'is'? 有没有办法只删除“是”?
I tried: s.replace(' is ', '')
with a space each side of 'is' but in this case 'is' is not removed in the string s = 'Isabelle is, as you know, in Paris'
我试过了:
s.replace(' is ', '')
,在'is'的每一侧都有一个空格,但是在这种情况下,不会在字符串s = 'Isabelle is, as you know, in Paris'
删除s = 'Isabelle is, as you know, in Paris'
Thank you 谢谢
Use a regular expression instead of replacing an ordinary string. 使用正则表达式而不是替换普通字符串。 You can then use
\\b
in the regexp to match word boundaries. 然后,您可以在正则表达式中使用
\\b
来匹配单词边界。
import re
s = re.sub(r'\bis\b', '', s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.