Fastest way to calculate leading whitespace
Daniel Skinner
dasacc22 at gmail.com
Sat May 8 13:48:06 EDT 2010
That solution actually runs slower then the generator method.
On Sat, May 8, 2010 at 12:33 PM, Shashank Singh <
shashank.sunny.singh at gmail.com> wrote:
>
>
> On Sat, May 8, 2010 at 10:49 PM, dasacc22 <dasacc22 at gmail.com> wrote:
>
>> Hi
>>
>> This is a simple question. I'm looking for the fastest way to
>> calculate the leading whitespace (as a string, ie ' ').
>>
>> Here are some different methods I have tried so far
>> --- solution 1
>>
>> a = ' some content\n'
>> b = a.strip()
>> c = ' '*(len(a)-len(b))
>>
>
> use lstrip if you want to remove leading whitespaces only.
> strip removes trailing white spaces too
>
>>
>> --- solution 2
>>
>> a = ' some content\n'
>> b = a.strip()
>> c = a.partition(b[0])[0]
>>
>> --- solution 3
>>
>> def get_leading_whitespace(s):
>> def _get():
>> for x in s:
>> if x != ' ':
>> break
>> yield x
>> return ''.join(_get())
>>
>
> why do you need a generator (and as you mentioned the extra function call
> overheads)?
>
> How about this?
>
> def get_leading_whitespaces(s):
> count = 0
> for c in s:
> if c != ' ': break
> count += 1
> return ' ' * count
>
>
>>
>> ---
>>
>> Solution 1 seems to be about as fast as solution 2 except in certain
>> circumstances where the value of b has already been determined for
>> other purposes. Solution 3 is slower due to the function overhead.
>>
>> Curious to see what other types of solutions people might have.
>>
>> Thanks,
>> Daniel
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> Regards
> Shashank Singh
> Senior Undergraduate, Department of Computer Science and Engineering
> Indian Institute of Technology Bombay
> shashank.sunny.singh at gmail.com
> http://www.cse.iitb.ac.in/~shashanksingh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100508/16686f50/attachment-0001.html>
More information about the Python-list
mailing list