Python Code To Check If String Contains Substring
Chapter:
Python
Last Updated:
24-09-2023 02:51:27 UTC
Program:
/* ............... START ............... */
# Using the in keyword:
main_string = "Hello, World!"
substring = "World"
if substring in main_string:
print("Substring found")
else:
print("Substring not found")
#Using the str.find() method:
main_string = "Hello, World!"
substring = "World"
if main_string.find(substring) != -1:
print("Substring found")
else:
print("Substring not found")
#Using the str.index() method (similar to str.find() but raises an exception if the substring is not found):
main_string = "Hello, World!"
substring = "World"
try:
index = main_string.index(substring)
print("Substring found at index:", index)
except ValueError:
print("Substring not found")
#Using regular expressions (requires the re module):
import re
main_string = "Hello, World!"
substring = "World"
if re.search(substring, main_string):
print("Substring found")
else:
print("Substring not found")
/* ............... END ............... */
Notes:
-
Choose the method that best fits your specific needs. The first two methods are the simplest for basic substring checks, while the third method provides more control and the fourth method is useful for more complex pattern matching using regular expressions.
Tags
Python code to check if string contains substring #How to Check if a Python String Contains a Substring