How to remove empty lines with re?
Anand Pillai
pythonguy at Hotpop.com
Sun Oct 12 10:43:00 EDT 2003
You probably did not read my posting completely.
I have added a comma after the print statement and mentioned
a comment specifically on this.
The 'print line,' statement with a comma after it does not print
a newline which you also call as line terminator whereas
the 'print' without a comma at the end does just that.
No wonder python sometimes feels like high-level psuedocode ;-)
It has that ultra intuitive feel for most of its tricks.
In this case, the comma is usually put when you have more than
one item to print, and python puts a newline after all items.
So it very intuitively follows that just putting a comma will not
print a newline! It is better than telling the programmer to use
another print function to avoid newlines, which you find in many
other 'un-pythonic' languages.
-Anand
Klaus Alexander Seistrup <spam at magnetic-ink.dk> wrote in message news:<3f86e96c-da7dc89b-addc-47d2-82cf-a60a482e6e07 at news.szn.dk>...
> Anand Pillai wrote:
>
> > Here is the complete code.
> >
> > import re
> >
> > empty=re.compile('^$')
> > for line in open('test.txt').readlines():
> > if empty.match(line):
> > continue
> > else:
> > print line,
>
> The .readlines() method retains any line terminators, and using the
> builtin print will suffix an extra line terminator to every line,
> thus effectively producing an empty line for every non-empty line.
> You'd want to use e.g. sys.stdout.write() instead of print.
>
>
> // Klaus
More information about the Python-list
mailing list