Searching Strings for Substrings


print searchStr.find("Red") print searchStr.rfind("Blue") print searchStr.index("Blue") print searchStr.index("Blue",8)

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



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net