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

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

This error typically occurs when you try to call the contains() method on a string object which does not exist.

Flowchart

Flowchart of Fixing the AttributeError: 'str' object has no attribute 'contains'

Reproducing the error

string = "Hello, World!"

print(string.contains("World"))

Output

Reproducing the AttributeError

How to fix it?

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

Solution 1: Using in operator

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 string.find()

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.