Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "AttributeError: 'str' object has no attribute 'sort'" occurs when
we try to call the sort()
method on a string. To solve the error, use the
sorted()
function if you need to sort a string alphabetically, or split the
words of the string and sort them.
Here is an example of how the error occurs.
my_str = 'cba' # ⛔️ AttributeError: 'str' object has no attribute 'sort' result = my_str.sort()
Strings don't have a sort()
method and are immutable in Python.
If you need to sort a string alphabetically, use the sorted()
function.
my_str = 'cba' result = ''.join(sorted(my_str)) print(result) # 👉️ "abc"
The sorted function returns a new sorted list from the items in the iterable.
my_str = 'cba' print(sorted(my_str)) # 👉️ ['a', 'b', 'c']
The last step is to join the list into a string without any separators.
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
If you need to sort the words in a string, split them into a list and call the
sort()
method on the list.
my_str = 'Carl Ben Alice' result = my_str.split(' ') print(result) # 👉️ ['Carl', 'Ben', 'Alice'] result.sort() print(result) # 👉️ ['Alice', 'Ben', 'Carl']
The str.split() method splits the original string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
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 sort()
is not a method implemented by strings, the error is caused.