How to Solve Python AttributeError: ‘str’ object has no attribute ‘sort’

by | Programming, Python, Tips

This error occurs when you try to sort a string by calling sort() directly on the string object. You can solve this error by using the built-in sorted() method, which returns a list, and then you can join the list into a string using the join() method. For example,

sorted_string = ''.join(sorted(string))

This tutorial will go through the error in detail and how to solve it with code examples.


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

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘str’ object has no attribute ‘sort’” tells us that the string object does not have the attribute sort().

The sort() method belongs to the List data type and sorts a list in ascending order by default. We can convert a string to a List using the split() method or the sorted() method.

We can check an object’s attributes by using the dir() function. The dir() function returns all the properties and methods of the specified object as a list.

Let’s verify that sort() is not a String method by using the in operator:

string = "test"

attributes = dir(string)

print("sort" in attributes)
False

Let’s prove that sort() is a List method by using the in operator:

lst = [1, 2, 3]
attributes = dir(lst)

print("sort" in attributes)
True

Example #1

Let’s look at an example of a string we want to sort in alphabetical order.

my_str = 'python'

print(my_str.sort())

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [4], in <cell line: 3>()
      1 my_str = 'python'
----> 3 print(my_str.sort())

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

The error occurs because sort is a List method, not a String method.

Solution

We can solve the error by using the sorted() method, which returns a sorted list.

my_str = 'python'

sorted_list = sorted(my_str)

print(sorted_list)

print(type(sorted_list))

Let’s run the code to see the list:

['h', 'n', 'o', 'p', 't', 'y']
<class 'list'>

We can convert the list back to a string using the join() method. The str.join() method takes an iterable as an argument and joins the items in the iterable into one string.

sorted_str = ''.join(sorted_list)
print(sorted_str)
print(type(sorted_str))

Let’s run the code to get the result:

hnopty
<class 'str'>

We successfully sorted the string in alphabetical order.

We can put the above code together in one line as follows:

sorted_str = ''.join(sorted(my_str))
print(sorted_str)
print(type(sorted_str))
hnopty
<class 'str'>

Example #2

Let’s look at another example where we have a string containing the names of five programming languages separated by a single whitespace. We want to sort these language names in alphabetical order. Let’s try to call the sort() method on the string:

languages = 'Python C++ Go Rust Java'

sorted_languages = languages.sort()

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [8], in <cell line: 3>()
      1 languages = 'Python C++ Go Rust Java'
----> 3 sorted_languages = languages.sort()

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

The error occurs because the sort() method belongs to the List data type, not String.

Solution

We can solve this error by converting the languages object from a string to a list using split. The str.split() method splits the original string into a list of substrings using a delimiter. We will single whitespace as the delimiter. Let’s look at the revised code:

languages = 'Python C++ Go Rust Java'

languages_list = languages.split(' ')

print(languages_list)

Let’s run the code to see the list:

['Python', 'C++', 'Go', 'Rust', 'Java']

Next, we can sort the list by calling the sort() method.

languages_list.sort()
print(languages_list)
['C++', 'Go', 'Java', 'Python', 'Rust']

We successfully sorted the programming language names in alphabetical order.

Summary

Congratulations on reading to the end of this tutorial! The AttribueError: ‘str’ object has no attribute ‘sort’ occurs when you call the sort() method on a string object. Ensure that you check the object type before calling the sort() method using the type() function.

For further reading on AttributeErrors, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee