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

Bob Gailer bgailer at alum.rpi.edu
Sat Jul 21 05:48:22 CEST 2007


Luke Paireepinart wrote:
> Terry Carroll wrote:
>   
>> Is there a straightforward way to find out if all characters in one string 
>> are present in a second string?
>>
>> Basically, I have a string s, and I want to print it out only if every
>> character in it is printable (because I accidentally brought my PC loudly
>> to its knees printing a few thousand BEL characters when trying to debug
>> something).  A workable test for me is whether every character in the
>> string to be printed is in string.printable.
>>
>> Right now I'm doing:
>>
>> def printable(s):
>>     import string
>>     return [x for x in s if x not in string.printable] == []
>>   
>>     
If you are only concerned about the first 32 ascii characters 
(non-printable) then this might be more efficient (since it compares 
each character to ' ' and stops at the first non-printable):

import itertools
testString = 'aso;dkfj hado;fg ja;lsfj asl;fj jf asdl; fj\g'
candidate = [x for x in itertools.takewhile(lambda x : x >= ' ', s)]
if len(candidate) == len(testString):
    print testString

-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC




More information about the Tutor mailing list