简体   繁体   中英

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'. 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. Also, no need for the if check; 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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