views:

67

answers:

1

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.

+1  A: 

re.sub doesn'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:

text = open("myfile.txt").read()
# This is your original re.sub call, but I'm not sure it really does what you want.
text = re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text)
text = re.sub('this \(a_zA_Z0_9)+ another replacement', 'some other thing', text)
open("myfile.txt", "w").write(text)
Ned Batchelder
can you please show me with the above example ,how can i do that . Thanks
kdev
Thanks Ned , actually that was my main question , as how can i have two different string replaced so re.sub('this \(a_zA_Z0_9)+ a statement', '\1trim', text),re.sub('this is fun','this is notfun',file)so in short can two re.sub work in a single line or not ? if not how to accomplish this part.Thanks again for your help.
kdev
There's no need to do both replacements in one line, simply call re.sub twice as I've edited the answer. Don't forget to accept it if it works for you! :)
Ned Batchelder