regex to remove lines made of only whitespace

Tim Chase python.list at tim.thechases.com
Wed Aug 11 13:33:15 CEST 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. 
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







More information about the Python-list mailing list