How to find the first space?

J

Johny

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)

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

Thanks
L.
 
D

Diez B. Roggisch

Russell said:
Why do you need to use a regex?

text = text.replace(" ", "")

You are aware that this is producing nonsense given the OP's requirements?
Thisisasample

Instead, the OP wants
This is a sample

Diez
 
D

Diez B. Roggisch

Johny said:
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)

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

Use the strip-method, as defined on stringlike objects.

Diez
 
M

Maric Michaud

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.



--
_____________

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
 
C

Chris

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)

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

Thanks
L.

If it's leading spaces you're worried about you can use the .lstrip()
method, if you want to find the first space you can use .index(' ') to
get the position of it and do with what you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top