I basically have strings that might be like this
str1 = "Z (X) Z"
str2 = "Z .X. Z"
str3 = "Z 'X' Z"
The X might be anything, as well as Z: for example:
str1 = "(example1) "
str2 = "random_stuff .example2. other_random_stuff"
str3 = "'example3' stuff"
What I need is to replace the X with something else, but how can I do that if the X could be anything? I have to extrapolate the portion of string delimited by "..", "()", "''" (the X portion) and replace it with something else. Z portions can be anything as well and they should not be considered, and the X thing can be found in the middle of the string as well so i cant use this:
str1 = ".X."
str_to_be_changed = str1[1][-1]
str1.replace(str_to_be_changed, "Y")
Thanks :)
You'd use a regular expression with a replacement function:
import re
def change_string(string, replacement):
def repl(match):
o, c = match.group('open'), match.group('close')
if o + c in ('..', "''", '()'):
return '{}{}{}'.format(o, replacement, c)
return match.group(0)
return re.sub(r"(?P<open>['.(]).*?(?P<close>['.)])", repl, string)
The repl()
function verifies that the opener and closing characters match up before replacing.
Demo:
>>> str1 = ".X."
>>> change_string(str1, 'Y')
'.Y.'
>>> change_string("This is a larger 'example' with (more than one) replacement, including a 'false positive.", 'Y')
"This is a larger 'Y' with (Y) replacement, including a 'false positive."
Try using str.format()
For example:
l = ".{}."
print l.format("mything")
'.mything.'
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.