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

Dave Kuhlman dkuhlman at rexx.com
Sat Jul 21 05:03:42 CEST 2007


On Fri, Jul 20, 2007 at 06:46:13PM -0700, 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] == []
> 

Try thinking about a regular expression.  Something along the lines
of:

    pattern = r'[^%s]' % string.printable
    re_pattern = re.compile(pattern)

    match_obj = re_pattern.search(s)
    if match_obj:
        o
        o
        o

Notice the carrot (^) just inside the square bracket.  That
reverses the pattern to all not in string.printable.  You will have
to work with this.  I have not tested it.

For more on regular expressions, see:

    http://docs.python.org/lib/re-syntax.html
    http://docs.python.org/lib/node46.html

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list