Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
July 31, 2023
Python does not have a built-in contains method for strings. However, there are a few ways to check if a string contains a substring.
One way is to use the in operator. The in operator returns True if the substring is found in the string, and False if it is not found. For example, the following code checks if the string “hello” contains the substring “ell”:
string = "hello" substring = "ell" if substring in string: print("The substring is found") else: print("The substring is not found")
This code will print the following output:
The substring is found
Another way to check if a string contains a substring is to use the index() method. The index() method returns the index of the first occurrence of the substring in the string. If the substring is not found, the index() method will raise a ValueError exception. For example, the following code checks if the string “hello” contains the substring “ell”:
string = "hello" substring = "ell" index = string.index(substring) if index != -1: print("The substring is found at index", index) else: print("The substring is not found")
This code will also print the following output:
The substring is found at index 2
Finally, you can also use the re module to check if a string contains a substring. The re module provides a number of functions for working with regular expressions. For example, the following code checks if the string “hello” contains the substring “ell” using a regular expression:
import re string = "hello" substring = "ell" pattern = r"ell" if re.search(pattern, string): print("The substring is found") else: print("The substring is not found")
This code will also print the following output:
The substring is found
There are a few ways to check if a string contains a substring in Python. The best method to use will depend on your specific needs.