Newbie question: string replace

Steve Holden steve at holdenweb.com
Fri Oct 28 20:18:09 CEST 2005


usgog at yahoo.com wrote:
> Now it works:
> rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)')
> for line in fileinput.input(FILE, inplace=1):
>      m = rex.match(line)
>      if m is not None:
>          line = "%s%s%s\n" % (m.group(1), new_name, m.group(3))
>      print line
> 
> But there is an extra line break after each line in FILE. Why is that?
> I tried to line = "%s%s%s" % (m.group(1), new_name, m.group(3)) but it
> turns out there are two extra line breaks after each line...
> 
 >>> for l in open('wshtest1.pys'):
...     print repr(l)
...
'import sys\n'
'# WScript.Echo(str(sys.modules))\n'
'\n'
'from msg import Message\n'
'Message("Hello")\n'
'\n'
 >>>

As yoyu can see, iterating over a (text) file gives you lines with a 
line ending. Print adds a line ending as well. Instead use

import sys
     ...
     ...
     ...
     sys.stdout.write(l)

You will find you lose the blank lines.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list