Test a string for a substring

Question:

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

Asked By: Nate

||

Answers:

if "ABCD" in "xxxxABCDyyyy":
    # whatever
Answered By: Sven Marnach

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
Answered By: kurumi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.