searching for strings (in a tuple) in a string

Simon Forman rogue_pedro at yahoo.com
Thu Jul 6 11:09:56 EDT 2006


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:
>    < ...>
>
> 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.
>
> Is there a way around this?

One thing I do sometimes is to check for True in a generator
comprehension

if True in (t in a for t in tup):
    # do whatever here


Because you're using a generator you get the same "short-circut"
behavior that you would with a series of 'or's, the if statement won't
bother checking the rest of the terms in tup after the first True
value.

>>> def f(n, m):
	print n
	return n > m

>>> m = 2
>>> if True in (f(n, m) for n in range(5)):
	print 'done'


0
1
2
3
done

# See?  No 4!  :-)


I usually use this with assert statements when I need to check a
sequence. Rather than:

for something in something_else: assert expression

I say

assert False not in (expression for something in something_else)

This way the whole assert statement will be removed if you use the '-O'
switch to the python interpreter.  (It just occurred to me that that's
just an assumption on my part.  I don't know for sure that the
interpreter isn't smart enough to remove the first form as well.  I
should check that. ;P )

Note, in python 2.5 you could just say

if any(t in a for t in tup):
    # do whatever here


In your case though, if I were doing this kind of thing a lot, I would
use a little helper function like the findany() function Fredrik Lundh
posted.

IMHO

if findany(a, tup):
    ...

is much clearer and readily understandable than mucking about with
generator comprehensions...


Peace,
~Simon




More information about the Python-list mailing list