Skip to main content
python find in string

Various Methods for Finding a Substring in a String

This python tutorial will assist you in understanding python string functionality through examples. We will use Python to find a substring in a string in a variety of ways.

Python’s main package is a string. We will determine whether a word or character in a Python string exists or not.

The python has find, index, and in method to find the substring and character into the target string.

Checkout other python String tutorials:

in Operator

Python has an operator that checks whether a character exists or not in the source string. To find characters in a string, use the in operator.

How To Use python find() method

The python has find() method to check substring into the string. The Python String find() method is used to find the index of a substring in a string. You can find substring in a string by this method.

s = "This is a boy."
if s.find("is") == -1:
   print("No 'is' here!")
else:
print("Found 'is' in the string.")

The code above will output “Found ‘is’ in the string.” When the substring is found in the string, this method returns the index number. When the substring is not found, it returns -1.

This method is useful when you want to know the index position of the substring.

How To Use Python in Operator

The python has in operator to check character or substring into the string. The in operator returns the True value when the substring exists in the string. Otherwise, it returns false.

s = "This is a boy"
"is" in s
True
"Is" in s
False

It would print True. Similarly, if "is" in s: would evaluate to True.

Python not in operator

Let’s see a not in operator in Python with example.

s = "I love python programming."
if "is" not in s: 
    print('is not exist in the String.')
else:
    print('It exists.')

Python index method use

Python String index() is an function that returns the index of a substring. The index() method finds the first occurrence of the substring into the source string. The index() method raises the exception if the value is not found. An index() method is almost the same as the find() method, the only difference is that find() method returns -1 if that value is not found.

s = "I love python programming."
isexist = s.index('love')
print(isexist)

The python index returns the lowest index of a found substring. If substring doesn’t exist inside the string, it raises a ValueError exception.

Leave a Reply

Your email address will not be published. Required fields are marked *