Determine Whether a String Contains a Substring in Python

This can be done simply using the “find” method. If the value is found, the first index of that value is returned. If it is not found, -1 is returned.

def contains(theString, theQueryValue):
  return theString.find(theQueryValue) > -1

x = “abcdefg”

print contains(x, “abc”) // True
print contains(x, “xyz”) //False

2 Responses to “Determine Whether a String Contains a Substring in Python”

  1. http://docs.python.org/library/string.html#deprecated-string-functions

  2. bah, the instance method is not being deprecated; anyhoo, (‘foo’ in ‘barfoo’)

Leave a Reply