135

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Nate
  • 17,918
  • 26
  • 69
  • 93

2 Answers2

219
if "ABCD" in "xxxxABCDyyyy":
    # whatever
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
  • 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
35

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
  • 12,395
  • 17
  • 43
  • 69
kurumi
  • 24,217
  • 4
  • 43
  • 49
  • 5
    The last one requires and `re.escape` call in the general case though. –  Mar 29 '11 at 13:28