Checking a string against multiple matches

Peter Otten __peter__ at web.de
Mon Dec 1 14:52:08 EST 2008


Aaron Scott wrote:

> I've been trying to read up on this, but I'm not sure what the
> simplest way to do it is.
> 
> I have a list of string. I'd like to check to see if any of the
> strings in that list matches another string.
> 
> Pseudocode:
> 
> if "two" in ["one", "two", "three", "four"]:
>      return True

Why /pseudo/ ?

>>> if "two" in ["one", "two", "three", "four"]:
...     print "match"
... else:
...     print "no match"
...
match
>>> if "seven" in ["one", "two", "three", "four"]:
...     print "match"
... else:
...     print "no match"
...
no match
 
> Is there any built-in iteration that would do such a thing, or do I
> have to write a function to check for me? I was using .index on the
> list, but it would return True for strings that contained the search
> string rather than match it exactly, leading to false positives in my
> code.

You didn't check carefully. list.index() gives you a value error when no
matching item is found:

>>> ["one", "two", "three", "four"].index("seven")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

Peter



More information about the Python-list mailing list