Fastest way to calculate leading whitespace
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat May 8 15:46:56 EDT 2010
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.
--
Steven
More information about the Python-list
mailing list