🌐
Reddit
reddit.com › r/learnpython › how to sort a string alphabetically?
r/learnpython on Reddit: How to sort a string alphabetically?
February 13, 2021 -

If I have a string "cab", I want to sort the string alphabetically to get "abc". The sorted() function returns a list instead of a string. For example, I tried the following:

str = "cab"
sorted_str = sorted(str)
print(sorted_str)

and it prints ['a', 'b', 'c'] instead of 'abc'. I can use a for loop to create another string like this and it prints 'abc', but it's cumbersome:

new_sorted_str = ''
for i in range(len(sorted_str)):
    new_sorted_str += sorted_str[i]
print(new_sorted_str) 

Is there a better way?

.

Top answer
1 of 11
598

Basic answer:

Copymylist = ["b", "C", "A"]
mylist.sort()

This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:

Copyfor x in sorted(mylist):
    print x

However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).

So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):

Copysorted(mylist, key=cmp_to_key(locale.strcoll))

And finally, if you need, you can specify a custom locale for sorting:

Copyimport locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']

Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:

Copy# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
2 of 11
64

It is also worth noting the sorted() function:

Copyfor x in sorted(list):
    print x

This returns a new, sorted version of a list without changing the original list.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-sort-a-string
Python Program to Sort a String - GeeksforGeeks
July 11, 2025 - sorted() function is the most efficient way to sort a string. It returns a sorted list of characters which we can then join back into a single string. This method is concise and efficient as it uses Python's built-in functions.
🌐
W3Schools
w3schools.com › python › ref_func_sorted.asp
Python sorted() Function
Remove List Duplicates Reverse ... Interview Q&A Python Bootcamp Python Training ... The sorted() function returns a sorted list of the specified iterable object....
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-sort.html
Python Sorting
>>> sorted(strs, reverse=True) ['zebra', 'donut', 'banana', 'apple'] By default in Python, uppercase chars come before lowercase chars, so uppercase strings will sort to the front of the list:
🌐
Python documentation
docs.python.org › 3 › howto › sorting.html
Sorting Techniques — Python 3.14.6 documentation
The list.sort() method and the functions sorted(), min(), max(), heapq.nsmallest(), and heapq.nlargest() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
🌐
Real Python
realpython.com › python-sort
How to Use sorted() and .sort() in Python – Real Python
February 24, 2025 - Just like before, you can use sorted() to iterate through each element of the iterable you pass in. In a string, each element means each character, including spaces. Note: Python sorts strings lexicographically by comparing Unicode code points ...
Find elsewhere
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to sort a string in python?
How to Sort a String in Python | Analytics Vidhya
October 17, 2024 - To sort a string using this approach, we can convert the string into a list of characters, sort the list using the sort() method, and then join the sorted characters back into a string.
🌐
Google
developers.google.com › google for education › python › python sorting
Python Sorting | Python Education | Google for Developers
July 23, 2024 - The key function takes in 1 value ... sort. For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest....
🌐
The Renegade Coder
therenegadecoder.com › code › how-to-sort-a-list-of-strings-in-python
How to Sort a List of Strings in Python: Sort, Sorted, and More – The Renegade Coder
May 26, 2020 - Why sort by hand when we can leverage the high-level power of python? Naturally, python has a built in sort functionality that works by accepting a list and sorting it in place. Let’s see what it does for a list of strings:
🌐
HackerEarth
hackerearth.com › practice
Programming tutorials, Coding problems, and Practice questions
Topological Sort · Hamiltonian Path · Maximum flow · Minimum Cost Maximum Flow · Min-cut · String Algorithms · Basics of String Manipulation · String Searching · Z Algorithm · Manachar’s Algorithm · Dynamic Programming · Introduction to Dynamic Programming 1 ·
🌐
codemahal
codemahal.com › sorting-lists-strings-python
Sorting lists and strings in Python — codemahal
Strings can also be sorted into ascending or descending order. With strings, we use the sorted() function. It takes the string we wish to sort as a parameter and also has a second optional parameter to specify if the string should be sorted in reverse order.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-reverse-sort-a-string
Reverse Sort a String - Python - GeeksforGeeks
July 12, 2025 - If we are working with a string that has been converted into a list, we can use sort() method to reverse sort it in place. This method is slightly faster for large strings as it avoids creating a new list. Python · s = "geeksforgeeks" # Convert string to list and reverse sort a = list(s) a.sort(reverse=True) res = "".join(a) print(res) Output ·
🌐
Quora
quora.com › How-do-I-sort-a-string-alphabetically-in-Python-without-using-the-sort-function
How to sort a string alphabetically in Python without using the sort function - Quora
Answer (1 of 12): Essentially every question of the form: “How do I X without using the (built-in or standard feature) Y?” is a waste of time when posted to public forums. These are generally academic assignments. How do you implement a sort function? You don’t have to do this for any ...
🌐
OKX
okx.com › docs-v5 › en
OKX API guide | OKX technical support | OKX
Retrieve the account’s bills. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with most recent first.
🌐
ACTE
acte.in › home › learn how to sort a string in python
Sort A Strings In Python: sorted(), And Examples | Updated 2026
CyberSecurity Framework and Implementation Article
Explore How To Sort A Strings In Python ⭐Using sorted(), Handle Case Sensitivity, Convert Strings To Lists, Sort Words vs Characters, And Manage Unicode One of best Institute to learn CyberSecurity Framework and Implementation from ACTE . Really impressive model where you can learn technical Skills , Soft Skill and get help to kick start your first Job as well.
Rating: 5 ​
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-given-list-of-strings-by-part-of-string
Python | Sort given list of strings by part of string - GeeksforGeeks
July 11, 2025 - This method uses the list.sort() function to sort the list in place and while sorting it applies it uses a lambda function to extract the second word from each string as the sorting key.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-numeric-strings-in-a-list
Sort Numeric Strings in a List - Python - GeeksforGeeks
July 11, 2025 - a = ["10", "2", "30", "4"] # Naive approach: using nested loops to sort the list in-place for i in range(len(a)): for j in range(i + 1, len(a)): if int(a[i]) > int(a[j]): a[i], a[j] = a[j], a[i] print(a)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-each-string-in-string-list
Python | Sort each String in String list - GeeksforGeeks
April 9, 2023 - In this, we use sorted() functionality to perform sort operation and join() is used to reconstruct the string list. ... # Python3 code to demonstrate working of # Sort Strings in String list # using list comprehension + sorted() + join() # ...