How to Search within a String in Python - dummies

How to Search within a String in Python

By John Paul Mueller

There are times with Python when you need to locate specific information in a string. For example, you may want to know whether a string contains the word Hello in it. One of the essential purposes behind creating and maintaining data is to be able to search it later to locate specific bits of information.

Strings are no different — they’re most useful when you can find what you need quickly and without any problems. Python provides a number of functions for searching strings. Here are the most commonly used functions:

  • count(str, beg= 0, end=len(string)): Counts how many times str occurs in a string. You can limit the search by specifying a beginning index using beg or an ending index using end.

  • endswith(suffix, beg=0, end=len(string)): Returns True when a string ends with the characters specified by suffix. You can limit the check by specifying a beginning index using beg or an ending index using end.

  • find(str, beg=0, end=len(string)): Determines whether str occurs in a string and outputs the index of the location. You can limit the search by specifying a beginning index using beg or a ending index using end.

  • index(str, beg=0, end=len(string)): Provides the same functionality as find(), but raises an exception when str isn’t found.

  • replace(old, new [, max]): Replaces all occurrences of the character sequence specified by old in a string with the character sequence specified by new. You can limit the number of replacements by specifying a value for max.

  • rfind(str, beg=0, end=len(string)): Provides the same functionality as find(), but searches backward from the end of the string instead of the beginning.

  • rindex(str, beg=0, end=len(string)): Provides the same functionality as index(), but searches backward from the end of the string instead of the beginning.

  • startswith(prefix, beg=0, end=len(string)): Returns True when a string begins with the characters specified by prefix. You can limit the check by specifying a beginning index using beg or an ending index using end.

Finding the data that you need is an essential programming task — one that is required no matter what kind of application you create. The following steps help you create an example that demonstrates the use of search functionality within strings.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    SearchMe = "The apple is red and the berry is blue!"
    print(SearchMe.find("is"))
    print(SearchMe.rfind("is"))
    print(SearchMe.count("is"))
    print(SearchMe.startswith("The"))
    print(SearchMe.endswith("The"))
    print(SearchMe.replace("apple", "car")
      .replace("berry", "truck"))

    The example begins by creating SearchMe, a string with two instances of the word is. The two instances are important because they demonstrate how searches differ depending on where you start. When using find(), the example starts from the beginning of the string. By contrast, rfind() starts from the end of the string.

    Of course, you won’t always know how many times a certain set of characters appears in a string. The count() function lets you determine this value.

    Depending on the kind of data you work with, sometimes the data is heavily formatted and you can use a particular pattern to your advantage. For example, you can determine whether a particular string (or substring) ends or begins with a specific sequence of characters. You could just as easily use this technique to look for a part number.

    The final bit of code replaces apple with car and berry with truck. Notice the technique used to place the code on two lines. In some cases, your code will need to appear on multiple lines to make it more readable.

  3. Choose Run→Run Module.

    You see a Python Shell window open. Notice especially that the searches returned different indexes based on where they started in the string. Using the correct function when performing searches is essential to ensure that you get the results you expected.

    image0.jpg