Python String Find Substring – Check String Contains Substring

In this article, we will discuss various methods to check substring in python string.

There are two ways to check substring in python.

Using the in operator

The simplest way to check the substring python string is using the in operator. To test the membership we can use in and not in operators.

For strings, x in y is True if and only if x is a substring of y. let’s understand this with an example as shown below.

message = "This is a test"

#To check message string contains test substring
if "test" in message:
    print("Message contains test")

Output

Message contains test

The in operator helps to check the existence of substring(test) in the message.

Also, note that empty strings(“”) are considered to be a substring of any string. So “” in “hello” will return True.

Using the string.find method

Another way to check substring using the string’s find method.

The syntax of string.find method

str.find(sub, start, end)

Parameters

  • sub – Substring to check
  • start – Start index for the search ( optional)
  • end – End index for the search (optional)

Returns the lowest index where the substring is found and returns -1 if the sub is not found.

message = "This is a test"

index = message.find("test")

if index >-1:
   print(f"The test string found at index {index}")

#This will return -1
index_ = message.find("news")
print(index_)

Output

The test string found at index 10
-1

Conclusion

Use the in operator to check the string contains substring and use string.find method when we need to know the position of the substring.

Leave a Comment