AttributeError: 'str' object has no attribute 'reverse'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

AttributeError: 'str' object has no attribute 'reverse' #

The Python "AttributeError: 'str' object has no attribute 'reverse'" occurs when we call the reverse() method on a string. To solve the error, use string slicing to reverse a string, e.g. 'abc'[::-1].

attributeerror str object has no attribute reverse

Here is an example of how the error occurs.

main.py
my_str = 'apple' # ⛔️ AttributeError: 'str' object has no attribute 'reverse' print(my_str.reverse())

Strings don't have a reverse() method in Python, however we can use string slicing to reverse a string.

main.py
my_str = 'apple' reversed_str = my_str[::-1] print(reversed_str) # 👉️ "elppa"

The syntax for string slicing is my_str[start:stop:step].

We omitted the indices for start and stop because we want the whole string.

We used -1 for the step which means that we step from the end of the string towards the beginning 1 character at a time.

The original string remains unchanged, so make sure to store the reversed string in a variable.

main.py
my_str = 'abc' reversed_str = my_str[::-1] print(reversed_str) # 👉️ "cba" print(my_str) # 👉️ "abc"

Note that lists have a reverse() method in Python.

main.py
my_list = ['a', 'b', 'c'] my_list.reverse() print(my_list) # 👉️ ['c', 'b', 'a']

The list.reverse() method reverses the elements of the list in place.

The method returns None because it mutates the original list.

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
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))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

Since the str object doesn't implement a reverse() method, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.