String functions: what's the difference?

Harro de Jong h.c.de.jong at xxxxmsnet.nl.invalid
Thu Mar 9 14:54:04 CET 2006


(absolute beginner here, sorry if this seems basic)

Section 7.10 of 'How to Think Like a Computer Scientist' contains this 
discussion of string.find and other string functions: 

(quote)
We can use these constants and find to classify characters. For example, if
find(lowercase, ch) returns a value other than -1, then ch must be lowercase:

def isLower(ch):
return string.find(string.lowercase, ch) != -1

Alternatively, we can take advantage of the in operator, which determines
whether a character appears in a string:
def isLower(ch):
return ch in string.lowercase

As yet another alternative, we can use the comparison operator:
def isLower(ch):
return 'a' <= ch <= 'z'
If ch is between a and z, it must be a lowercase letter.

As an exercise, discuss which version of isLower you think will be
fastest. Can you think of other reasons besides speed to prefer one
or the other?

(end quote)

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. 

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? 
And reasons to prefer one? a-z doesn't contain all lowercase letters (it omits 
acents and symbols), but other than that? 


-- 
Harro de Jong
remove the extra Xs from xmsnet to mail me



More information about the Python-list mailing list