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!