Fastest way to calculate leading whitespace

Mark Dickinson dickinsm at gmail.com
Sat May 8 16:46:59 EDT 2010


On May 8, 8:46 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote:
> > On 8 Mai, 20:46, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au>
> > wrote:
>
> >> def get_leading_whitespace(s):
> >>     t = s.lstrip()
> >>     return s[:len(s)-len(t)]
>
> >> >>> c = get_leading_whitespace(a)
> >> >>> assert c == leading_whitespace
>
> >> Unless your strings are very large, this is likely to be faster than
> >> any other pure-Python solution you can come up with.
>
> > Returning s[:-1 - len(t)] is faster.
>
> I'm sure it is. Unfortunately, it's also incorrect.
>
> >>> z = "*****abcde"
> >>> z[:-1-5]
> '****'
> >>> z[:len(z)-5]
>
> '*****'
>
> However, s[:-len(t)] should be both faster and correct.

Unless len(t) == 0, surely?

--
Mark



More information about the Python-list mailing list