‘str’ object has no attribute ‘contains’ ( Solved )

str' object has no attribute 'contains'

While coding and using the string variable you can get the error like ‘str’ object has no attribute ‘contains’. If yes then this post is for you. In this entire tutorial, you will know what is the cause and how to solve this AttributeError in a simple way.

The root cause of  AttributeError: ‘str’ object has no attribute ‘contains’

The main and root cause of the error Root cause of ‘str’ object has no attribute ‘contains’ is that you are calling the contains()  method which is not provided by the string.  Most of the time coder use contains()  method to find the substring in the existing string using this method which is wrong.

You will get the ‘str’ object has no attribute ‘contains’ error when you will run the below lines of code.

my_str = 'hello world'
print(my_str.contains('world'))

Output

str object has no attribute contains
no attribute contains error

Solution of ‘str’ object has no attribute ‘contains’ Error

The solution to the above error is that you don’t have to use the contains() method to find the sub-string in the string. Instead of it use the “in” operator to check the existence of the sub-string in the string.

Let’s say I have to check whether the “Data” sub-string is present in “Welcome to the Data Science Learner” or not then I will use the “in” operator to check.

my_string = "Welcome to the Data Science Learner"
print("Data" in my_string)

Output

True

The statement “Data” in my_string will return True or False depending on the match of the sub-string.

You can also use the “in ” operator in the if-else or another loop. It will act as the condition for that loop.

my_string = "Welcome to the Data Science Learner"
if "Data" in my_string:
    print("Substring exists in String")
else:
    print("Substring not exists in String")

OutputUsing the in operator for the statment checking in the loop

Conclusion

You can solve this AttributError no attribute ‘contains’ error if you use the” in ” operator instead of the contains() method for checking the existence of a sub-string in a string.  If you are getting error for the above cases then the method used here will solve the error.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner