That solution actually runs slower then the generator method.<br><br><div class="gmail_quote">On Sat, May 8, 2010 at 12:33 PM, Shashank Singh <span dir="ltr"><<a href="mailto:shashank.sunny.singh@gmail.com">shashank.sunny.singh@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;"><br><br><div class="gmail_quote">On Sat, May 8, 2010 at 10:49 PM, dasacc22 <span dir="ltr"><<a href="mailto:dasacc22@gmail.com" target="_blank">dasacc22@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204, 204, 204);padding-left:1ex">

Hi<br>
<br>
This is a simple question. I'm looking for the fastest way to<br>
calculate the leading whitespace (as a string, ie '    ').<br>
<br>
Here are some different methods I have tried so far<br>
--- solution 1<br>
<br>
a = '    some content\n'<br>
b = a.strip()<br>
c = ' '*(len(a)-len(b))<br></blockquote><div><br>use lstrip if you want to remove leading whitespaces only.<br>strip removes trailing white spaces too<br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204, 204, 204);padding-left:1ex">



<br>
--- solution 2<br>
<br>
a = '    some content\n'<br>
b = a.strip()<br>
c = a.partition(b[0])[0]<br>
<br>
--- solution 3<br>
<br>
def get_leading_whitespace(s):<br>
    def _get():<br>
        for x in s:<br>
            if x != ' ':<br>
                break<br>
            yield x<br>
    return ''.join(_get())<br></blockquote><div><br>why do you need a generator (and as you mentioned the extra function call overheads)?<br><br>How about this?<br><br>def get_leading_whitespaces(s):<br>    count = 0<br>


    for c in s:<br>        if c != ' ': break<br>        count += 1<br>    return ' ' * count<br>   <br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204, 204, 204);padding-left:1ex">



<br>
---<br>
<br>
Solution 1 seems to be about as fast as solution 2 except in certain<br>
circumstances where the value of b has already been determined for<br>
other purposes. Solution 3 is slower due to the function overhead.<br>
<br>
Curious to see what other types of solutions people might have.<br>
<br>
Thanks,<br>
Daniel<br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br><br clear="all"><br>-- <br>Regards<br>Shashank Singh<br>Senior Undergraduate, Department of Computer Science and Engineering<br>Indian Institute of Technology Bombay<br><a href="mailto:shashank.sunny.singh@gmail.com" target="_blank">shashank.sunny.singh@gmail.com</a><br>


<a href="http://www.cse.iitb.ac.in/~shashanksingh" target="_blank">http://www.cse.iitb.ac.in/~shashanksingh</a><br>
</blockquote></div><br>