If I have a file contents like this:
old_string
-old_string
I want to change only "old_string" to be "+new_string" so the result looks like
+new_string
-old_string
my code gives this result:
+new_string
-+new_string
This is my code :
with open(filename) as f:
s = f.read()
if old_string not in s:
return False
with open(filename, 'w') as f:
s = s.replace(old_string, new_string)
f.write(s)
return True
i Tried regex, but it won't work since I pass the regex as a variables, this is what I did so far:
with open (filename, 'r' ) as f:
content = f.read()
content_new = re.sub('(\%old_string)', r'\new_string'%(old_string,new_string), content, flags = re.M)