替换python中的确切子字符串 [英] Replace exact substring in python

查看:40
本文介绍了替换python中的确切子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例字符串:德里办公室管理"

我想用空格替换字符串中的 in.但是当我这样做时,s.replace('in',""),管理的输入也变成空白.

这只是一个示例.要替换的字符串和单词可能会有所不同.

有没有办法只替换完全匹配的内容?

解决方案

您可以使用正则表达式 \bin\b.\b 这里的意思是 字边界.\bin\b 将匹配被单词边界(空格、标点符号等)包围的 in,而不是 in 换句话说.><预><代码>>>>进口重新>>>re.sub(r'\bin\b', '', '德里办公室管理')'办公室行政德里'

请参阅re.sub.

Example string: "office administration in delhi"

I want to replace in from the string with a blank. But when I do, s.replace('in',""), the in of administration also becomes blank.

This is just a sample. The string and the word to replace may vary.

Is there some way to replace only the exact match?

解决方案

You can use regular expression \bin\b. \b here means word boundary. \bin\b will match in surrounded by word boundary (space, punctuation, ...), not in in other words.

>>> import re
>>> re.sub(r'\bin\b', '', 'office administration in delhi')
'office administration  delhi'

See re.sub.

这篇关于替换python中的确切子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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