By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,758 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

How do I count the number of spaces at the left end of a string?

P: n/a
I don't know exactly what the first non-space character is. I know the
first non-space character will be * or an alphanumeric character.

May 16 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
I don't know exactly what the first non-space character is. I know the
first non-space character will be * or an alphanumeric character.
How about:
>>mystring = ' ksjfkfjkfjds '
print len( mystring ) - len( mystring.lstrip( ) )
4
HTH,
Daniel
May 16 '07 #2

P: n/a
walterbyrd wrote:
I don't know exactly what the first non-space character is. I know the
first non-space character will be * or an alphanumeric character.
This is another of the hundreds of ways:

pyfor i,c in enumerate(astring):
.... if c != ' ': break
....
pyprint i
May 16 '07 #3

P: n/a
walterbyrd wrote:
I don't know exactly what the first non-space character is. I know the
first non-space character will be * or an alphanumeric character.

using builtin function rindex
st = 'asblde '
>>st.rindex(' ')
sph
--
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

May 16 '07 #4

P: n/a
On May 17, 8:18 am, Steven Howe <howe.ste...@gmail.comwrote:
walterbyrd wrote:
I don't know exactly what the first non-space character is. I know the
first non-space character will be * or an alphanumeric character.

using builtin function rindex
But only if there is a guarantee that are spaces nowhere else in the
string:

a = ' abc'
print a.rindex(' ') + 1
=4

Good, but ...

b = ' ab c'
b.rindex(' ') + 1
=7
Ouch!

The difference method suggested by Daniel Nogradi, seems the most
obvious way.

len(b) - len(b.lstrip())
=4

Asun

May 17 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.