Skip to main content
HomeAbout PythonLearn Python

Python String Contains

Sep 2020  · 5 min read

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.

Substring Search

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.

Substring Search

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.

Check out our Python String Tutorial.

Topics

Python Courses

Course

Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

A Beginner’s Guide to Data Cleaning in Python

Explore the principles of data cleaning in Python and discover the importance of preparing your data for analysis by addressing common issues such as missing values, outliers, duplicates, and inconsistencies.
Amberle McKee's photo

Amberle McKee

11 min

Python Data Classes: A Comprehensive Tutorial

A beginner-friendly tutorial on Python data classes and how to use them in practice
Bex Tuychiev's photo

Bex Tuychiev

9 min

Estimating The Cost of GPT Using The tiktoken Library in Python

Learn to manage GPT model costs with tiktoken in Python. Explore tokenization, BPE, and estimate OpenAI API expenses efficiently.
Moez Ali's photo

Moez Ali

7 min

Python Private Methods Explained

Learn about private methods in Python, their syntax, how and when to use them in your projects using examples, and the best practices.
Arunn Thevapalan's photo

Arunn Thevapalan

9 min

See MoreSee More