How to Fix the AttributeError: ‘str’ object has no attribute ‘contains’

To fix the AttributeError: ‘str’ object has no attribute ‘contains’, you can use the “in” operator or “find()” method to check if a substring is present in a given string.

Python raises the AttributeError: ‘str’ object has no attribute ‘contains’ when you try to call the contains() method on a string object which does not exist.

Reproducing the error

string = "Hello, World!"

try:
  string.contains("World")
except AttributeError as e:
  print(e)

Output

'str' object has no attribute 'contains'

In this code, we are trying to call the non-existent ‘contains’ method on the ‘string’ object, which will raise an AttributeError. The ‘except’ block catches the error and prints its description.

Fixing the error

You can use the “in” operator or “string.find()” method to fix the AttributeError because it helps you check if a substring is present in a given string.

Solution 1: Using the “in” operator

string = "Hello, World!"
substring = "World"

if substring in string:
  print("Substring found in the string.")
else:
  print("Substring not found in the string.")

Output

Substring found in the string.

Solution 2: Using the “string.find()” method

You can use the string.find() method that returns the starting index of the first occurrence of the substring if found and -1 if not found.

string = "Hello, World!"
substring = "World"

if string.count(substring) > 0:
  print("Substring found in the string.")
else:
  print("Substring not found in the string.")

Output

Substring found in the string.

I hope these solutions help you resolve your error.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.