How to Check If a String Contains a Substring in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string contains a substring in Python. The lab guides you through defining substrings using slicing with both positive and negative indices. You'll create a Python script named substrings.py to extract substrings from a given string and print them to the console.

The lab demonstrates how to use slicing to define substrings, extracting portions of a string by specifying start and end indices. You will learn to extract substrings like "Hello" and "LabEx" from the string "Hello, LabEx!" and also how to access the last character of the string using negative indexing. The lab includes instructions on running the script and verifying the output.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") subgraph Lab Skills python/strings -.-> lab-559567{{"How to Check If a String Contains a Substring in Python"}} python/conditional_statements -.-> lab-559567{{"How to Check If a String Contains a Substring in Python"}} end

Define Substrings

In this step, you will learn how to define substrings in Python. A substring is a contiguous sequence of characters within a string. Understanding how to work with substrings is essential for many string manipulation tasks.

Let's start by creating a Python script called substrings.py in your ~/project directory. You can use the VS Code editor to create this file.

## ~/project/substrings.py
string = "Hello, LabEx!"

This script initializes a string variable named string with the value "Hello, LabEx!".

Now, let's add some code to extract substrings from this string. A simple way to define a substring is by using slicing. Slicing allows you to extract a portion of a string by specifying the start and end indices.

Add the following lines to your substrings.py file:

## ~/project/substrings.py
string = "Hello, LabEx!"

substring1 = string[0:5]  ## Characters from index 0 to 4
substring2 = string[7:12] ## Characters from index 7 to 11

print(substring1)
print(substring2)

In this example, substring1 will contain the characters from index 0 up to (but not including) index 5, which is "Hello". substring2 will contain the characters from index 7 up to (but not including) index 12, which is "LabEx".

To run the script, open your terminal in VS Code and execute the following command:

python ~/project/substrings.py

You should see the following output:

Hello
LabEx

You can also use negative indices to define substrings. Negative indices count from the end of the string. For example, string[-1] refers to the last character of the string.

Modify your substrings.py file to include the following:

## ~/project/substrings.py
string = "Hello, LabEx!"

substring1 = string[0:5]  ## Characters from index 0 to 4
substring2 = string[7:12] ## Characters from index 7 to 11
substring3 = string[-1]   ## Last character

print(substring1)
print(substring2)
print(substring3)

Now, run the script again:

python ~/project/substrings.py

The output should now include the last character of the string:

Hello
LabEx
!

Understanding how to define substrings using slicing is a fundamental skill in Python. Experiment with different start and end indices to extract various parts of the string.

Use in Operator

In this step, you will learn how to use the in operator in Python to check if a substring exists within a string. The in operator is a simple and efficient way to determine the presence of a substring.

Let's continue working with the substrings.py file you created in the previous step. We'll add code to check if certain substrings are present in the original string.

Open the substrings.py file in your ~/project directory using the VS Code editor.

## ~/project/substrings.py
string = "Hello, LabEx!"

substring1 = "Hello"
substring2 = "Python"

print(substring1 in string)
print(substring2 in string)

In this example, we define two substrings, substring1 and substring2. We then use the in operator to check if each substring is present in the string variable. The in operator returns True if the substring is found, and False otherwise.

To run the script, open your terminal in VS Code and execute the following command:

python ~/project/substrings.py

You should see the following output:

True
False

This output indicates that "Hello" is present in the string "Hello, LabEx!", while "Python" is not.

You can also use the in operator in conditional statements. Modify your substrings.py file to include the following:

## ~/project/substrings.py
string = "Hello, LabEx!"

substring1 = "Hello"
substring2 = "Python"

if substring1 in string:
    print(f"'{substring1}' is found in '{string}'")
else:
    print(f"'{substring1}' is not found in '{string}'")

if substring2 in string:
    print(f"'{substring2}' is found in '{string}'")
else:
    print(f"'{substring2}' is not found in '{string}'")

Now, run the script again:

python ~/project/substrings.py

The output should now be more descriptive:

'Hello' is found in 'Hello, LabEx!'
'Python' is not found in 'Hello, LabEx!'

The in operator is a powerful tool for string manipulation in Python. It allows you to easily check for the presence of substrings within a string, making your code more readable and efficient.

Find Position with find()

In this step, you will learn how to use the find() method in Python to find the position of a substring within a string. The find() method returns the index of the first occurrence of the substring, or -1 if the substring is not found.

Let's continue working with the substrings.py file you created in the previous steps. We'll add code to find the position of specific substrings within the original string.

Open the substrings.py file in your ~/project directory using the VS Code editor.

## ~/project/substrings.py
string = "Hello, LabEx!"

substring1 = "LabEx"
substring2 = "Python"

position1 = string.find(substring1)
position2 = string.find(substring2)

print(position1)
print(position2)

In this example, we define two substrings, substring1 and substring2. We then use the find() method to find the position of each substring within the string variable.

To run the script, open your terminal in VS Code and execute the following command:

python ~/project/substrings.py

You should see the following output:

7
-1

This output indicates that "LabEx" is found at index 7 in the string "Hello, LabEx!", while "Python" is not found (indicated by -1).

You can also use the find() method with optional start and end indices to search for a substring within a specific range. Modify your substrings.py file to include the following:

## ~/project/substrings.py
string = "Hello, LabEx! LabEx"

substring1 = "LabEx"

position1 = string.find(substring1)         ## Find first occurrence
position2 = string.find(substring1, 8)      ## Find occurrence starting from index 8
position3 = string.find(substring1, 0, 5)   ## Find occurrence within the first 5 characters

print(position1)
print(position2)
print(position3)

Now, run the script again:

python ~/project/substrings.py

The output should now be:

7
14
-1

In this example:

  • position1 finds the first occurrence of "LabEx" at index 7.
  • position2 starts searching from index 8, so it finds the second occurrence of "LabEx" at index 14.
  • position3 searches within the first 5 characters of the string, so it doesn't find "LabEx" and returns -1.

The find() method is a versatile tool for locating substrings within a string. Understanding how to use it with optional start and end indices allows you to perform more targeted searches.

Summary

In this lab, you learned how to define substrings in Python using string slicing. You created a Python script to initialize a string and then extracted substrings by specifying start and end indices, including the use of negative indices to access characters from the end of the string. The lab demonstrated how to print these extracted substrings to the console.

The key takeaway is understanding how to use slicing with both positive and negative indices to define and extract specific portions of a string, which is a fundamental skill for string manipulation in Python.