How to find the first space?

Maric Michaud maric at aristote.info
Mon Jun 9 17:44:59 CEST 2008


Le Monday 09 June 2008 17:02:51 Johny, vous avez écrit :
> How can I find the first space using regex?
>
> For example I have text
> Text=' This is a sample '
>
> The last space I can remove by
> Text=re.sub(r"\s(?!\w)",'',Text)
>

For spaces at the end of line, I prefer this one :

re.sub(r'\s*$', '', s)

> but I do not know how to remove the first space.
> Can anyone help?

At the beginning :

re.sub(r'^\s*', '', s)

And the one that strip the whole line (not obvious) :

re.sub(r'\s*(\S+.*\S+)\s*', r'\1', s)


You really should consider s.strip(), rstrip(), lstrip()

String manipulation methods cover almost all use cases, and give better codes, 
keep regexes for what they are really valuable (parsing complex idioms, 
second step optimisation).

I can't even remember the last time I used re module in production code in 
python (unlike in perl or shell).

>
> Thanks
> L.
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21



More information about the Python-list mailing list