String functions: what's the difference?

"Martin v. Löwis" martin at v.loewis.de
Thu Mar 9 09:08:36 EST 2006


Harro de Jong wrote:
> I've tried all three, but the function is so small (test a single letter) I 
> can't measure the difference. I'm using time.time() to see how long it takes to 
> execute the function. 
> I could use a loop to increase execution time, but then I might be measuring 
> mostly overhead. 

Still, this is what you should do. Try the timeit.py module; it does the
loop for you. Surprisingly, one of the faster ways to do a loop is

nones = [None]*10000000

<start timer>
for x in nones:
  <action>
<stop timer>

This is fast because no Python integers are created to implement the
loop.

> I'd expect the third option to be the fastest (involves looking up 3 values, 
> where the others have to iterate through a-z), but am I right? 

Just measure it for yourself. I just did, and the third option indeed
came out fastest, with the "in" operator only slightly slower.

> And reasons to prefer one? 

For what purpose? To find out whether a letter is lower-case?

Just use the .islower() method on the character for that.

Regards,
Martin



More information about the Python-list mailing list