Let say i have a string like this ‘this is a statement’
and if i want to search and replace string with this ‘this ** a statement’
string to search for this is a statement , this si a statement , this i a statement and any combination convert them into this trim a statement
i.e for any word combination between this & a statement replace it with trim
for another set replace fun to notfun .
so this is the program
import re
file=open('file','r+')
search=re.sub('this \(a_zA_Z0_9)+ a statement','\1trim',file),('this is fun','this is notfun',file)
file.close()
something is not right as nothing is getting changed in the file.
thanks everyone.
re.subdoesn’t work on files, it works on strings. You need to read the contents of the file into a string, then use re.sub to change the string, then write the modified string back to the file.A simple example: