If you mean the first character without spaces, I would use something like this ...
>>> a=' Hello world' >>> len(a) - len(a.lstrip()) 3
Another fun:
>>> sum(1 for _ in itertools.takewhile(str.isspace,a)) 3
But I bet that the first version works faster, since this exact loop does it, only in C. Of course, he needs to build a new line when it is done, but it is essentially free.
For completeness, if a line is empty or consists of completely spaces, both of them will return len(a) (which is not true if you try to index with it ...)
>>> a = "foobar" >>> a[len(a)] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
source share