Fastest way to calculate leading whitespace

Stefan Behnel stefan_ml at behnel.de
Mon May 10 02:54:19 EDT 2010


dasacc22, 08.05.2010 19:19:
> This is a simple question. I'm looking for the fastest way to
> calculate the leading whitespace (as a string, ie '    ').

Here is an (untested) Cython 0.13 solution:

     from cpython.unicode cimport Py_UNICODE_ISSPACE

     def leading_whitespace(unicode ustring):
         cdef Py_ssize_t i
         cdef Py_UNICODE uchar

         for i, uchar in enumerate(ustring):
             if not Py_UNICODE_ISSPACE(uchar):
                return ustring[:i]
         return ustring

Cython compiles this to the obvious C code, so this should be impossible to 
beat in plain Python code.

However, since Cython 0.13 hasn't been officially released yet (may take 
another couple of weeks or so), you'll need to use the current developer 
version from here:

http://hg.cython.org/cython-devel

Stefan




More information about the Python-list mailing list