简体   繁体   English

替换匹配的单词python

[英]replace matching words python

I have this codition: 我有这个条件:

if "Exit" in name:
   replace_name = name.replace("Exit","`Exit`")
   name = replace_name

and it should replace Exit with 'Exit' but if I have another word like exited, it also replaces it 'Exit'. 并且它应该将Exit替换为“ Exit”,但是如果我有另一个词,如exited,它也将其替换为“ Exit”。 I only want it to replace the exact one "Exit" not exited. 我只希望它替换没有退出的确切“退出”。 what is the best way to overcome this issue? 解决此问题的最佳方法是什么?

Thanks. 谢谢。

You can use a regular expression with word boundary ( \\b ) characters. 您可以使用带有单词边界( \\b )字符的正则表达式 Also, no need for the if check; 另外,不需要if检查; if the word is not in the string, then nothing is replaced. 如果单词不在字符串中,则不会替换任何内容。

>>> import re
>>> s = "he exited through the exit"
>>> re.sub(r"\bexit\b", "'exit'", s)
"he exited through the 'exit'"

You could also use flags to make the match case insensitive, or use a callback function for determining the replacement 您还可以使用标志使区分大小写不敏感,或使用回调函数确定替换项

>>> s = "he exited through the Exit"
>>> re.sub(r"\b(exit)\b", lambda m: "'%s'"%m.group(1).upper(), s, flags=re.I)
"he exited through the 'EXIT'"

Use re for this. 为此使用re

import re
replaced_name=re.sub(r"\bExit\b","`Exit`",name)

Input: 输入:

name = ['dr.doom','spiderman',"Exit", 'exited']

if "Exit" in name:
    index = name.index("Exit")
    name.pop(index)
    name.insert(index, "'Exit'")

print(name)

Output: 输出:

['dr.doom', 'spinderman', "'Exit'", 'exited']

I should've wrote it this way: 我应该这样写:

if name == "Exit":
   replace_name = name.replace("Exit","`Exit`")
   name = replace_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM