Stripping whitespace

John Machin sjmachin at lexicon.net
Wed Jan 23 14:20:56 EST 2008


On Jan 24, 6:05 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> ryan k <r... at ryankaskel.com> writes:
> > Hello. I have a string like 'LNAME
> > PASTA               ZONE'. I want to create a list of those words and
> > basically replace all the whitespace between them with one space so i
> > could just do lala.split(). Thank you!
>
> import re
> s = 'LNAME  PASTA        ZONE'
> re.split('\s+', s)

That is (a) excessive for the OP's problem as stated and (b) unlike
str.split will cause him to cut you out of his will if his problem
turns out to include leading/trailing whitespace:

>>> lala = '   LNAME   PASTA   ZONE   '
>>> import re
>>> re.split(r'\s+', lala)
['', 'LNAME', 'PASTA', 'ZONE', '']
>>> lala.split()
['LNAME', 'PASTA', 'ZONE']
>>>



More information about the Python-list mailing list