Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
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]
.
Here is an example of how the error occurs.
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.
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.
-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.
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.
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.
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.
Since the str
object doesn't implement a reverse()
method, the error is
caused.