AttributeError: ‘str’ object has no attribute ‘contains’

Are you getting the error “attributeerror: ‘str’ object has no attribute ‘contains’“? Yes, you have come to the right place. Today in this tutorial, I will show you how to solve this error.

The error attributeerror: ‘str’ object has no attribute ‘contains’ occurs when we try to call the “contains()” on the string.

[Fixed] AttributeError: ‘str’ object has no attribute ‘contains’

You can fix this error by using the ‘in‘ operator instead of ‘contains‘ because there is no method ‘contains‘ in the python string.

You can get this error like this:

new_str = "EHTISHAM TARBELA"
# AttributeError: 'str' object has no attribute 'contains'
print(new_str.contains('TARBELA'))

You can use the “in” operator like this instead of contains() to get rid of this error:

new_str = "EHTISHAM TARBELA"
if 'EHTISHAM' in new_str :
    print('String contains: EHTISHAM')
else:
    print('EHTISHAM is NOT in the string')

Convert both strings to lowercase if you want to ignore the case when determining whether a substring is present in a string.

[Fixed]: TypeError: ‘generator’ object is not subscriptable in Python

str = 'ALI QAZIPUR'
substr = 'qaziPUR'

if substr.lower() in str.lower():
    print('string contains this substring')
else:
    print('string doesn't contains this substring')

If you want to check if the word is not available in the string you can use ‘not in’ in your code:

my_str = 'ALI QAZIPUR'

if 'Ehtisham' not in my_str:
    print('\'EHTISHAM\' is NOT in the string')
else:
    print('\'EHTISHAM\' is in the string')

AttributeError: ‘str’ object has no attribute ‘contains’ [Fixed]

The error “AttributeError:’str’ object has no attribute ‘contains’” occurs because the Python string does not have a method “contains().” You can check all methods using “dir()” in your Python code.

my_string = 'hello world!'

# [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
#  'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
#  'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
#  'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex',
#  'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
#  'title', 'translate', 'upper', 'zfill']

print(dir(my_string))

Conclusion on AttributeError: ‘str’ object has no attribute ‘contains’

Programmers, we discussed how we can solve errors “AttributeError: ‘str’ object has no attribute ‘contains’“. If you are still facing the error please let us know in the comments section. You can get rid of this error by using the ‘in’ operator in Python.

Leave a Reply