Faster 'if char in string' test

Kamilche klachemin at home.com
Thu Jun 24 10:50:13 EDT 2004


Pierre-Frédéric Caillaud <peufeu at free.fr> wrote in message news:<opr929m40e1v4ijd at musicbox>...

> why don't you use translate to delete all the valid characters and test  
> if the resulting string is not not empty ? this will save you two calls to  
> len()... heh heh

You're right, Pierre, that just might be more efficient! But I doubt
those two 'len' calls would show up on a profiler, somehow. ;-) But
you have to time it again, because the question becomes 'how efficient
is the translate function at removing invalid characters from a
string?' It might be much more efficient at removing one char, than at
removing a thousand. So the timings would still be necessary, to make
sure you're not optimizing the wrong part.

The 'dict' solution proposed wouldn't work because the data I'm
testing is in string form, and the overhead of translating the string
to a dict before testing would swamp the results. So would using a
set, because timings show a set is 4x slower than a dict.

Unless I'm misunderstanding Peter's suggestion. Did you mean
translating the string into a dict, then using a 'if boguschar in
dict' test?



More information about the Python-list mailing list