142

Is there an easy way to test a Python string "xxxxABCDyyyy" to see if "ABCD" is contained within it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nate
  • 18,892
  • 27
  • 70
  • 93

2 Answers2

224
if "ABCD" in "xxxxABCDyyyy":
    # whatever
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 5
    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. – 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
Sociopath
  • 13,068
  • 19
  • 47
  • 75
kurumi
  • 25,121
  • 5
  • 44
  • 52
  • 5
    The last one requires and `re.escape` call in the general case though. –  Mar 29 '11 at 13:28