Is there an easy way to test a Python string "xxxxABCDyyyy" to see if "ABCD" is contained within it?
Asked
Active
Viewed 2.9e+01k times
2 Answers
224
if "ABCD" in "xxxxABCDyyyy":
# whatever

Sven Marnach
- 574,206
- 118
- 941
- 841
-
5This 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. – GreenMatt Mar 29 '11 at 15:37
-
2@GreenMatt if you know it's a list just say `if 'ABCD' in list[0]`. – Jossie Calderon Jul 20 '16 at 13:08
36
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