In Python if you want to check if a given String is present in another String then you have following options-
- Use Python membership operators ‘in’ and ‘not in’. See example.
- Using find() method to check if string contains another string. See example.
- Using index() method to get the index of the substring with in the String. See example.
Python membership operators - in and not in
If you want to check if a String is member of another String then you can use ‘in’ and ‘not in’ membership operators.
- ‘in’ operator- Returns true if the string is part of another string otherwise false.
- ‘not in’ operator- Returns true if the string is not part of another string otherwise false.
Python in operator example
def check_membesrship(str1, str2): if str2 in str1: print(str2, 'found in String') else: print(str2, 'not found in String') str1 = "This is Python" str2 = "Python" check_membesrship(str1, str2) #another call check_membesrship(str1, 'That')
Output
Python found in String That not found in String
Python not in operator example
def check_membesrship(str1, str2): if str2 not in str1: print(str2, 'not found in String') else: print(str2, 'found in String') str1 = "This is Python" str2 = "Python" check_membesrship(str1, 'That') #another call check_membesrship(str1, str2)
Output
That not found in String Python found in String
Using find() method to check if substring exists in string
Using find() method in Python you can check if substring is part of the string or not. If found, this method returns the location of the first occurrence of the substring otherwise -1 is returned.
Python find() method example
def check_membesrship(str, substr): loc = str.find(substr) if loc == -1: print(substr, 'not found in String') else: print(substr, 'found in String at index', loc) str1 = "This is Python" str2 = "Python" check_membesrship(str1, str2) #another call check_membesrship(str1, 'That')
Output
Python found in String at index 8 That not found in String
Using index() method to check if substring exists in string
Using index() method in Python you can check if substring is part of the string or not. This method is similar to find() and returns the location of the first occurrence of the substring if found. If not found then index() method raises ‘ValueError’ exception that's where it differs from find().
Python index() method example
def check_membesrship(str, substr): # Catch ValueError exception try: loc = str.index(substr) except ValueError: print(substr, 'not found in String') else: print(substr, 'found in String at index', loc) str1 = "This is Python" str2 = "Python" check_membesrship(str1, str2) #another call check_membesrship(str1, 'That')
Output
Python found in String at index 8 That not found in String
That's all for this topic Check if String Present in Another String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-