Regular expression

Hans Nowak wurmy at earthlink.net
Tue Nov 27 00:57:12 EST 2001


Sang DeSibtis wrote:
> 
> import re,sys,string
> for line in open('junk', 'r').readlines ()
> a = re.compile('AAAA')
> b = re.compile('BBBB')
> 
> re.sub(a, 'aaaa', line)
> re.sub(b, 'bbbb', line)
> 
> print line   # nothing got changed
> 
> print re.sub(a, 'aaaa', line)   # works
> print re.sub(b, 'bbbb', line)    # works, however the line above
> doesn't work
> 
>  Questions: how do I make a global replacements in the 'line' that
> read from the file object (buffer in memory? ).Obviously, this is my
> first attemp at Python and I am not sure how things work. I want to
> replace all strings (not necessary 'AAAA' or 'BBBB' as illustrated
> here) in one pass. Will some one please explain in detail
> !!!!!!!!!!!!!!!!

re.sub gives you back a new string with the old string (pattern) 
replaced by the new one. It does not change the original string.
To apply the changes, simply do

  line = re.sub(a, 'aaaa', line)

etc...

HTH,

--Hans



More information about the Python-list mailing list