Tutorials
python

Python String Contains

If you are looking to find or replace items in a string, Python has several built-in methods that can help you search a target string for a specified substring.

.find() Method

Syntax

string.find(substring, start, end)

Note: start and end are optional arguments.

From the above syntax, you can observe that the .find() method takes the desired substring as the mandatory argument. You can specify the other two arguments: an inclusive starting position and an exclusive ending position.

In the example code, you search for Waldo in the string Where's Waldo?. The .find() method returns the lowest index in the string where it can find the substring, in this case, eight.

my_string = "Where's Waldo?"
my_string.find("Waldo")
8

If you search for Wenda, it returns -1 since the substring is not found.

my_string.find("Wenda")
-1

Let's see if you can find Waldo between characters zero and five. In the code, you specify the starting position zero and ending position as six, since this position is not inclusive.

my_string = "Where's Waldo?"
my_string.find("Waldo", 0, 6)
-1

The .find() method does not find the substring and returns -1, as shown above.

.index() Method

Syntax

string.index(substring, start, end)

Note: start and end are optional arguments.

From the above syntax, you can observe that the .index() method takes the desired substring as a mandatory argument. It can take optional starting and ending positions as well.

In the example, we search again for Waldo using .index().

my_string = "Where's Waldo?"
my_string.index("Waldo")
8

We get eight again. When we look for a substring that is not there, we have a difference.

my_string.index("Wenda")
File "<stdin>", line 1, in <module>
ValueError: substring not found

The .index() method raises an exception, as we can see in the output. We can handle this using the try except block.

my_string = "Where's Waldo?"
try:
    my_string.index("Wenda")
except ValueError:
      print("Not found")

Above, you can observe the syntax. The try part will test the given code. If any error appears, the except part will be executed, obtaining the following output as a result.

"Not found"

.count() Method

The .count() method searches for a specified substring in the target string. It returns the number of non-overlapping occurrences. In simple words, how many times the substring is present in the string.

Syntax

The syntax of .count() is very similar to the other methods, as we can observe.

string.count(substring, start, end)

Note: start and end are optional arguments.

Substring Count

In the example, we use the .count() method to get how many times fruit appears.

my_string = "How many fruits do you have in your fruit basket?"
my_string.count("fruit")
2

In the output, we see that is is two.

We can then limit the occurrences of fruit between character zero and fifteen of the string, as we can observe in the code below.

my_string.count("fruit", 0, 16)
1

The method will return 1. Remember that the starting position is inclusive, but the ending is not.

.replace Method

Sometimes you will want to replace occurrences of a substring with a new substring. In this case, Python provides us with the .replace method.

Syntax

string.replace(old, new, count)

Note: count is an optional argument.

As we see in the syntax above, it takes three arguments: the substring being replaced, the new string to replace it, and an optional number that indicates how many occurrences to replace.

Replacing a Substring

In the example code, we replace the substring house with car.

my_string = "The red house is between the blue house and the old house"
print(my_string.replace("house", "car"))
The red car is between the blue car and the old car

The method will return a copy with all house substrings replaced.

Replacing a Specific Number of Occurrences

In this example, we specified that we only want 2 of the occurrences to be replaced.

print(my_string.replace("house", "car", 2))
The red car is between the blue car and the old house

In the output, we see that the method returns a copy of the string with the first two occurrences of house replaced by car.

Interactive Example

In the below example, you will:

  • Find if the substring actor occurs between the characters with index 37 and 41 inclusive. If it is not detected, print the statement Word not found.
  • Replace actor actor with the substring actor if actor occurs only two repeated times.
  • Replace actor actor actor with the substring actor if actor appears three repeated times.
for movie in movies:
      # Find if actor occurrs between 37 and 41 inclusive
    if movie.find("actor", 37, 42) == -1:
        print("Word not found")
    # Count occurrences and replace two by one
    elif movie.count("actor") == 2:  
        print(movie.replace("actor actor", "actor"))
    else:
        # Replace three occurrences by one
        print(movie.replace("actor actor actor", "actor"))

When we run the above code, it produces the following result:

Word not found
I believe you I always said that the actor is amazing in every movie he has played
it's astonishing how frightening the actor norton looks with a shaved head and a swastika on his chest.

Try it for yourself.

To learn more about finding and replacing strings, please see this video from our course, Regular Expressions in Python.

This content is taken from DataCamp’s Regular Expressions in Python course by Maria Eugenia Inzaugarat.