startswith( prefix[, start[, end]]) Query

Tim Williams listserver at tdw.net
Thu Sep 6 17:29:47 CEST 2007


On 06/09/07, Bruno Desthuilliers
<bruno.42.desthuilliers at wtf.websiteburo.oops.com> wrote:
>
> You may want to try with a regexp, but I'm not sure it's worth it (hint:
> the timeit module is great for quick small benchmarks).
>
> Else, you could as well write your own testing function:
>
> def str_starts_with(astring, *prefixes):
>   startswith = astring.startswith
>   for prefix in prefixes:
>     if startswith(prefix):
>       return true
>   return false
>
> for line in f:
>   if str_starts_with(line, 'abc, 'de', 'xxx'):
>     # CODE HERE
>

Isn't slicing still faster than startswith?    As you mention timeit,
then you should probably add slicing to the pot too :)

if astring[:len(prefix)] == prefix:
     do_stuff()

:)



More information about the Python-list mailing list