Test a string for a substring

PythonString

Python Problem Overview


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

Python Solutions


Solution 1 - Python

if "ABCD" in "xxxxABCDyyyy":
    # whatever

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNateView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonkurumiView Answer on Stackoverflow