how to find whether a string is contained in another string

Try using find() instead - this will tell you where it is in the string:

a = '1234;5'
index = a.find('s')
if index == -1:
    print "Not found."
else:
    print "Found at index", index

If you just want to know whether the string is in there, you can use in:

>>> print 's' in a
False
>>> print 's' not in a
True

you can use in operator if you just want to check whether a substring is in a string.

if "s" in mystring:
   print "do something"

otherwise, you can use find() and check for -1 (not found) or using index()


str.find() and str.index() are nearly identical. the biggest difference is that when a string is not found, str.index() throws an error, like the one you got, while str.find() returns -1 as others' have posted.

there are 2 sister methods called str.rfind() and str.rindex() which start the search from the end of the string and work their way towards the beginning.

in addition, as others have already shown, the in operator (as well as not in) are perfectly valid as well.

finally, if you're trying to look for patterns within strings, you may consider regular expressions, although i think too many people use them when they're overkill. in other (famous) words, "now you have two problems."

that's it as far as all the info i have for now. however, if you are learning Python and/or learning programming, one highly useful exercise i give to my students is to try and build *find() and *index() in Python code yourself, or even in and not in (although as functions). you'll get good practice traversing through strings, and you'll have a better understanding as far as how the existing string methods work.

good luck!


print ('s' in a)     # False
print ('1234' in a)  # True

Use find if you need the index as well, but don't want an exception be raised.

print a.find('s')    # -1
print a.find('1234') # 0

Tags:

Python

String