Home » Learn to code » Python Str in Str: Does String Contain Another String?

Python Str in Str: Does String Contain Another String?

If you’re looking for a Python script to check if a string contains another string, look no further! In Python, there are a few ways to check if a string contains another string. In this blog post, we will show four different methods for doing so, and we will also provide Python code examples for each method.

When Do You Need to Check if a String Contains Another String?

There are some cases in which you may need to check if a string contains another string. For example, you may want to check whether a word exists in a sentence or if a substring is present in an email address.

String containment checks are useful for validations as well as tasks related to text manipulation and Natural Language Processing (NLP).

There are many other tasks that require confirmation of the presence of another string. For example, if you’re developing a search feature for your website, it’s important to verify whether the user’s query is included in the database.

Similarly, when crafting an automated message or email, verification ensures that all information comes from the same source.

Taking the time to double-check strings for accuracy may seem tedious, but it can often mean the difference between success and failure in user input or data manipulation.

Ultimately, verification will help you ensure that your project runs smoothly and you can move on to other tasks with peace of mind.

Checking Python Str in Str - if Python String contains another String
Photo by AltumCode @ Unsplash

The in Operator

The easiest and most efficient way to check if a String contains another String is by using the in operator. It’s simple, easy to read, and it can be used for a range of tasks.

The syntax of the in operator is simple: String1 in String2 will return True if String2 contains String1. It will return False otherwise (returns boolean value).

Let’s look at an example. We have two strings:

string1 = “Python”
string2 = “I love Python programming”

If we check if String1 is contained in String2 with the in operator, we will get a result of True.

string1 in string2
>>True

This is because String2 contains String1. The in operator makes it easy to quickly identify if String2 contains String1 or not.

See also  Top 10 Most Popular Programming Languages 2024

The opposite of in operator is the not in operator, which is used to check if the Substring is NOT a part of the larger String. For example,

string1 = “Java”
string2 = “I love Python programming”

string1 in string2
>>False

The in and not in operators are often used with conditionals to evaluate a String’s containment status. As an example, if you want to print out a String if it is contained within another String, you can use the following code:

string1 = "programming"
string2 = "Python is the best programming language"

if string1 in string2:
  print(string1)

>>programming

One important thing to note is that Strings are case-sensitive with the in operator. If String2 contains String1 with a different casing, the in operator will return False. For example,

string1 = "Python"
string2 = "I love python programming"

String1 in String2
>>False

In order to bypass this problem if you do not care about the casing of the words and just want to know whether a word appears in the text in any form, you could format the whole larger String into lowercase letter and then run the in operator. For example,

string1 = "python"
string2 = "I Love Python Programming"
string2_lowercase = string2.lower()

string1 in String2_lowercase
>>True

When it’s best to use the in operator:

  1. For quick and easy String containment checks
  2. When casing may be important
  3. For validations and text manipulation tasks
  4. When you don’t need any information about the Substring other than that it exists somewhere in the main String.

The index() Method

The index() method works similarly to the in operator. However, it also gives us information about where in the main String does the Substring occur. It returns the position of a Substring inside of a String as an integer. If the Substring is not found, a ValueError exception is thrown.

Let’s look at an example:

string1 = "I love Python"
string2 = "Python"

try:
    string1.index(string2)
except ValueError:
    print("Substring not found!")
else:
    print("Substring found!")

The index() method will return the integer 7 because String1 contains String2 and String2 start at the 7th character in String1. This will in turn result in the output of “Substring found!”.

The start and end parameters:

We can also specify the index from which the method should start looking for String2 within String1. This can be done using the start and end parameters as follows:

string1 = "I love Python"
string2 = "Python"
start_index = 3
end_index = 9

try:
    string1.index(string2, start_index, end_index)
except ValueError:
    print("Substring not found")
else:
    print("Substring found!")

In this case, String2 will not be found because String2 does not appear in String1 within the specified range (it occurs in the range of 7 and 12, which is not fully included in the range specified in the index() method).

See also  5 Ways To Find Part-Time Programming Jobs in 2024

When it’s best to use the index() method:

  1. When you need to find the exact position of a Substring within a String
  2. When you need the index of where String1 is found in String2
  3. When you need to perform String manipulations within a range

The find() Method

The find() method works similarly to the index() method, with the main difference being that find() returns -1 when String2 is not found, instead of raising an exception. This is quite convenient, as you don’t have to handle exceptions this way. Let’s look at an example:

string1 = "I love Python"
string2 = "Python"

string1.find(string2)
>>7

The find() method will return the integer 7, just like the index() method. If we try to find a nonexistent Substring, we get:

string1 = "I love Python"
string2 = "Ruby"

string1.find(string2)
>>-1

We can also specify start and end indices the same way we did with the index() method:

string1 = "I love Python"
string2 = "love"
start_index =5
end_index = 10

string1.find(string2, start_index, end_index)
>>-1

Here, the find() method returned -1 because String2 is not found in String1 within the specified range.

When it’s best to use the find() method:

  1. When you want quick String containment checks with no exceptions
  2. When you need the index of String1 within String2
  3. When you want to manipulate String content within a range
  4. When you need to find the exact position of a Substring within String1.

The count() Method

The String count() method can also be used to check if a String contains another String. This method returns the number of times a Substring appears in the String. For example,

string1 = "Python is my favorite programming language. I love Python programming."
string2 = "Python"

string2.count(string1)
>>2

Here, String1 contains String2 twice. Therefore, the String count() method returns 2.

The start and end index parameters are also available for use with the String count() method, just like with the String index() and String find() methods.

When it’s best to use the count() method:

  1. When you need to count the number of occurrences of String2 in String1
  2. When you want to check if String1 contains String2
  3. When you need to perform String manipulations within a range
  4. When you want quick String containment checks without exceptions.
See also  Is 8GB of RAM Enough For Programming? (Hint: For Now…)

In summary, the String index(), String find(), and String count() methods are all useful when you need to check if a String contains another String. Each method has its own advantages and disadvantages and is best used in different scenarios, as we mentioned in each method.

Regex

Finally, you can also use Regex (Regular Expressions) to check if String1 contains String2. This is a more complex, yet powerful way to check String content and is widely used in many programming languages. Let’s take a look at an example:

import re

string1 = "I love Python programming."
string2 = "Python"

if re.search(string2, string1):
    print("String found!")
else:
    print("String not found")

>> String found!

Here, we use the re.search() method and pass String2 as the first argument and String1 as the second argument. This method returns a Regex match object if String2 is found in String1, and None otherwise.

When it’s best to use Regex:

  1. When String2 is too complex for String index() or String find() methods
  2. When String2 is only a part of String1
  3. When String2 needs to follow certain patterns
  4. For case-insensitive matching.

Conclusion

In this article, we explored the in operator, String index(), String find(), and String count() methods, as well as Regex, for checking if a String contains another String (Python Str in Str). Each method has its own advantages and disadvantages and should be used depending on the scenario. We hope this article was helpful in understanding String containment in Python. Good luck and thanks for reading!