[Tutor] How to determine if every character in one string is inanother string?

wesley chun wescpy at gmail.com
Mon Jul 23 22:46:25 CEST 2007


> > > > all(char in string.printable for char in testString)
>
> That was my favorite, too.  I didn't notice the new all method in 2.5.  It
> certainly seems the most Pythonic approach.


all() has a sister built-in function, also introduced in 2.5, so i
think that any(char not in string.printable for char in testString)
will work too.

however, believe it or not, i kinda like your original answer... it's
not as lame as you think! :-) i tweaked it slightly (for performance
reasons) to:

from string import printable as prglobal
def printable(s):
    prlocal = prglobal
    for x in s:
        if x not in prlocal:
            return False
    return True

- i got rid of the list comp and the list comparisons... they're not
necessary and slow things down

- i moved the import outside the function... not sure why i did this.
must be leftover from the days i used to think that the import would
occur every time the function's called, but now i know that there's a
difference between "importing" and "loading" of a module!

- i also created a local reference to string.printable to speed up the
lookup -- recall the name resolution order is: locals, globals,
built-ins

- i also also short-circuit the rest of the string if/when it finds
the 1st non-printable. (no need to go on in a 10-million character
string if char#2 is a non-printable right?)

the solutions using LCs above are great when it comes to an expressive
piece of code in a one-liner, but i feel there's a waste of
time/memory.  the use of GEs is better, but it still has to iterate
over the entire string when i don't feel that it should be necessary
as per my example. anyway, just my $0.02! not the shortest, but
hopefully the fastest!

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list