searching for strings (in a tuple) in a string

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Jul 7 10:04:05 EDT 2006


On Thu, 06 Jul 2006 04:45:35 -0700, manstey wrote:

> Hi,
> 
> I often use:
> 
> a='yy'
> tup=('x','yy','asd')
> if a in tup:
>    <...>
> 
> but I can't find an equivalent code for:
> 
> a='xfsdfyysd asd x'
> tup=('x','yy','asd')
> if tup in a:
>    < ...>

Of course you can't. Strings don't contain tuples, since they are utterly
different kinds of objects.

> I can only do:
> 
> if 'x' in a or 'yy' in a or 'asd' in a:
>    <...>
> 
> but then I can't make the if clause dependent on changing value of tup.

Sure you can.

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
for item in tup:
    if item not in a:
        print "Item missing"
        break
else:
    print "All items found."

It's a little verbose, but you can stick it into a function definition and
use it as a one-liner.

Or, use a list comprehension:

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
if [item for item in tup if item in a]:
    print "Some items found."
else:
    print "No items found."

Or, you can use filter:

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
if filter(lambda item, a=a: item in a, tup):
    print "Some items found."
else:
    print "No items found."


However, keep in mind that "in" has a subtly different effect in strings
and tuples. 

"x" in ("x", "y") is true, but "x" in ("xy", "yy") is not, as you would
expect. However, the situation for strings isn't quite the same:
"x" in "x y" is true, but so is "x" in "xx yy".

One way around that is to convert your string a into a list:

a = 'xfsdfyysd asd x'
a = a.split()  # split on any whitespace

and now your tests will behave as you expected.



-- 
Steven.




More information about the Python-list mailing list