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

W

walterbyrd

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.
 
D

Daniel Nogradi

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:
4


HTH,
Daniel
 
J

James Stroud

walterbyrd said:
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:

py> for i,c in enumerate(astring):
.... if c != ' ': break
....
py> print i
 
S

Steven Howe

walterbyrd said:
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 '
sph
 
A

Asun Friere

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
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top