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

Kent Johnson kent37 at tds.net
Tue Jul 24 04:30:14 CEST 2007

wesley chun wrote:

> from string import printable as prglobal
> def printable(s):
>     prlocal = prglobal
>     for x in s:
>         if x not in prlocal:
>             return False
>     return True
> 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!

any() and all() also short-circuit, and they move the iteration out of 
Python into the C runtime. My guess is the solutions with any() and 
all() and equivalent hoisting of string.printable will be faster than 
yours, but I don't want to take the time to check ATM...I would also try 
using set(string.printable) instead of string.printable...

Anyone feel like spending some time with timeit? Otherwise we're just 
guessing anyway.


More information about the Tutor mailing list