Given two strings, check whether a substring is in the given string. For Example:
Input:s ="geeks for geeks",s2 = "geeks"
Output: yes
Let's explore different ways to check if a string contains substring in Python.
Using in Operator
The in operator in Python checks if one string occurs within another. It evaluates to True if the substring is present in the main string, otherwise False.
Pythons="Geeks welcome to the Geek Kingdom!"if"Geek"ins:print("Substring found!")else:print("Substring not found!")if"For"ins:print("Substring found!")else:print("Substring not found!")OutputSubstring found!Substring not found!
Explanation:
- "Geek" in s: checks if the substring "Geek" exists in text.
- "For" in s: checks for "For" in text.
Using operator.contains() Method
The operator.contains() function checks for substring presence in a string programmatically. It provides the same result as the in operator but belongs to Python’s operator module, making it useful in functional programming contexts.
Pythonimportoperatorasops="Geeks welcome to the Geek Kingdom!"s2="Geek"ifop.contains(s,s2):print("Yes")else:print("No")Explanation:op.contains(s, s2) returns True if s2 is found within s, otherwise False.
Using find() Method
The find() method scans the string to locate a specific substring. It returns the starting index of the first occurrence if found; otherwise, it returns -1. This makes it useful for verifying substring presence and identifying its position within a string.
Pythons="Geeks welcome to the Geek Kingdom!"s2="Geek"ifs.find(s2)!=-1:print("Yes")else:print("No")Explanation:
- s.find(s2) searches for s2 within string.
- If the method returns a value other than -1, it means the substring exists.
- Returning -1 indicates that the substring is not present.
Using index() Method
The index() method works similarly to find() but raises a ValueError if the substring does not exist in the string. It is useful when you need the exact position of the substring and want an explicit error if it’s missing.
Pythons="Geeks welcome to the Geek Kingdom!"print(s.index("Kingdom"))Explanation:
- s.index("Kingdom") returns the position of the first occurrence of 'Kingdom' in s.
- If 'Kingdom' does not exist, it raises a ValueError.
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice