regex to remove lines made of only whitespace

Andreas Tawn andreas.tawn at ubisoft.com
Wed Aug 11 07:39:27 EDT 2010


> On 08/11/10 06:21, Andreas Tawn wrote:
> >> I'm looking for a regex (or other solution, as long as it's quick!)
> >> that could be used to strip out lines made up entirely of
> whitespace.
> >>
> >> eg:
> >>
> >> 'x\n \t \n\ny' ->  'x\ny'
> >
> > for line in lines:
> >      if not line.strip():
> >          continue
> >      doStuff(line)
> 
> Note that the OP's input and output were a single string.

Ah, indeed. What do they say about the first part of assume?

> Perhaps something like
>  >>> s = 'x\n \t \n\ny'
>  >>> '\n'.join(line for line in s.splitlines() if line.strip())
> 'x\ny'
> 
> which, IMHO, has much greater clarity than any regexp with the
> added bonus of fewer regexp edge-cases (blanks at the
> beginning/middle/end of the text).
> 
> -tkc

This what I meant (no really) ;o).

Cheers,

Drea





More information about the Python-list mailing list