Is there an easy way to test a Python string "xxxxABCDyyyy" to see if "ABCD" is contained within it?
2 Answers
if "ABCD" in "xxxxABCDyyyy":
# whatever
2 Comments
GreenMatt
This works here, but may not give the expected results if you are testing against a non-string. E.g. if testing against a list of strings (perhaps with
if "ABCD" in ["xxxxabcdyyyy"]), this can fail silently.Jossie Calderon
@GreenMatt if you know it's a list just say
if 'ABCD' in list[0].There are several other ways, besides using the in operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found