
Does Python have a string ‘contains’ substring method?
Yes. Python has an inbuilt string method contains() which helps find if a string contains a specific substring or not.
Syntax:
demostring.__contains__(substring)
The function takes in two strings, the original string and the substring whose presence is to be checked. It returns a boolean value, True if the substring is present in the string, else False.
Example:
string_demo= "Python by i2tutorials" sub_string_1="Python" sub_string_2="Java" result= string_demo.__contains__(sub_string_1) result_2= string_demo.__contains__(sub_string_2) print(result) print(result_2)
Output:
We can use this string contains method as a class method too. The syntax for the same looks like this:
str.__contains__(demostring,substring)
Example:
string_demo= "Python by i2tutorials" sub_string_1="Python" sub_string_2="Java" result= str.__contains__(string_demo,sub_string_1) result_2= str.__contains__(string_demo,sub_string_2) print(result) print(result_2)
Output:
This method raises TypeError exception when the demo string points to None.
Example:
string_demo= None sub_string="Python" result= str.__contains__(string_demo,sub_string) print(result)
Output:
To avoid this, we have to check whether our demo string points to None or not. Here, we use an if-else statement to do this.
Example:
string_demo= None sub_string="Python" if string_demo != None: print(str.__contains__(string_demo,sub_string_1)) else: print("The demo string is empty")
Output:
Share: