Check string for substring?

Is there an easy way to check the Python string “xxxxABCDyyyy” to see if it contains “ABCD”?

+72
python string
Mar 29 '11 at 13:10
source share
2 answers
if "ABCD" in "xxxxABCDyyyy": # whatever 
+158
Mar 29 '11 at 13:10
source share

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 
+27
Mar 29 '11 at 13:19
source share



All Articles