How to Check if a Python String Contains Another String ?

Last Updated On Saturday 28th May 2022

python string contains

in operator

  • We Can use the keyword in.
  • It’s a build-in python functionality
  • Using in is Efficient, Clean Readable way
	string = "I Love Tom & Jerry"

print("Tom" in string)
# True

python string contains substring

In the Above Example, Tom is the substring in our original string string, So the result is true.If you search for a substring that does not exist in original string, it returns `false

string contains python

	string = "I Love Tom & Jerry"

print("Puma" in string)
# False

.find() Method

  • We can use the function find.
  • Basically, it’s a String method.
	string = "I Love Tom & Jerry"

# 13
  • It Doesn’t return boolean & it returns the index
  • If we search for a string that doesn’t exist, it returns -1.
  • It always returns the index of that substring or -1 if that doesn’t exist
  • We can specify the start index & stop index
	string = "I Love Tom & Jerry"

# -1

re – python regex

  • Uses the regular expression package re.
  • This is Advanced Method for Advanced functionality

python findall

	import re

string = "I Love Tom & Jerry.Tom loves Scooby"


# ['Tom', 'Tom']
  • We found all occurrences string Tom in our original string
  • This is the most PowerFul Function
  • We can also use the search method from package re, It also gives an index of the string

python search

	import re

string = "I Love Tom & Jerry.Tom loves Scooby"


# <re.Match object; span=(7, 10), match='Tom'>
  • Yes, It gives a start index & a stop index. But it doesn’t find all the strings.
python contains string
python string contains string
python string contain
if string contains python
python string contains another string
string contains in python
.contains python
string contain python
python string includes
a string contains another string python
check if string contains python
string contains python3