The two most common ways to search for a substring contained inside another string are the find(sub, [, start, [,end]])) and index(sub, [, start, [,end]]) methods. The index method is faster than the find method; however, if the substring is not found in the string, an exception is thrown. If the find method fails to find the substring, then a -1 is returned. The find and index methods accept a search string as the first argument. The area of the string that is searched can be limited by specifying the optional start and/or end index. Only characters within those indexes will be searched. Python also provides the rfind and rindex methods. These methods work in a similar manner as the find and index methods; however, they look for the right-most occurrence of the substring. searchStr = "Red Blue Violet Green Blue Yellow Black" print searchStr.find("Red") print searchStr.rfind("Blue") print searchStr.find("Blue") print searchStr.find("Teal") print searchStr.index("Blue") print searchStr.index("Blue",20) print searchStr.rindex("Blue") print searchStr.rindex("Blue",1,18) search_str.py 0 22 4 -1 4 22 22 4 Output from search_str.py code |