How to sort a string in Python
Learn to sort a string in Python with various methods. Explore tips, real-world applications, and how to debug common sorting errors.

Developers often need to sort strings in Python. The language provides built-in tools like the sorted() function that make character order simple and efficient for various applications.
Here, you’ll find several techniques to sort strings, with practical tips, real-world applications, and debugging advice to help you master string manipulation for your specific use cases.
Using sorted() and join() to sort a string
text = "python"
sorted_text = ''.join(sorted(text))
print(sorted_text)--OUTPUT--hnopty
The sorted() function is the key to this operation. It treats the string as an iterable sequence of characters and returns a new list with those characters sorted alphabetically. For the string "python", this results in the list ['h', 'n', 'o', 'p', 't', 'y'].
Since sorted() outputs a list, you need to convert it back into a string. That’s where the join() method comes in. Calling join() on an empty string—''—concatenates every item from the list with no separator, reassembling the characters into a single, sorted string.
Basic string sorting techniques
Beyond the basic sorted() and join() combination, you can refine your sorting with explicit list conversion, reverse ordering, and in-line filtering using list comprehensions.
Sorting a string with list() conversion
text = "hello"
char_list = list(text)
char_list.sort()
sorted_text = ''.join(char_list)
print(sorted_text)--OUTPUT--ehllo
You can also sort a string by first explicitly converting it into a list using the list() function. This approach gives you a mutable list of characters to work with directly.
- The key difference is using the list's
sort()method, which modifies the list in place. - This contrasts with the
sorted()function, which returns a new sorted list without changing the original iterable.
After sorting the list, you just use ''.join() to reassemble the characters into the final string.
Sorting a string in reverse order with the reverse parameter
text = "python"
reverse_sorted = ''.join(sorted(text, reverse=True))
print(reverse_sorted)--OUTPUT--ytponh
For descending order, simply add the reverse=True argument to the sorted() function. This parameter flips the default alphabetical sort (A to Z) to a reverse alphabetical sort (Z to A).
- It’s a clean, one-step modification to the standard sorting pattern you've already seen.
The function processes the string and arranges the characters in reverse, which you then reassemble into a final string using ''.join().
Using list comprehension for filtering while sorting
text = "Hello123"
# Sort only alphabetic characters
letters = [c for c in text if c.isalpha()]
sorted_letters = ''.join(sorted(letters))
print(sorted_letters)--OUTPUT--Hellllo
List comprehensions offer a concise way to build a new list while filtering elements from an iterable. The expression [c for c in text if c.isalpha()] creates a new list containing only the alphabetic characters from the original string, effectively filtering out the numbers.
- The
if c.isalpha()condition is the key; it acts as a filter, telling Python to only include characters that are letters. - Once you have this filtered list, you can sort it and join it back into a string using the methods you've already seen.
Advanced string sorting techniques
To move beyond simple alphabetical sorting, you can use the key parameter with custom functions to implement more complex logic, like case-insensitive or custom ordering, especially when working with AI-powered Python development.
Case-insensitive sorting with the key parameter
text = "Hello World"
case_insensitive = ''.join(sorted(text, key=str.lower))
print(case_insensitive)--OUTPUT--deHllloorW
By default, Python sorts uppercase letters before lowercase ones. The key parameter in sorted() provides a way to override this behavior. When you use key=str.lower, you're telling the function to look at the lowercase version of each character when it decides the order.
This effectively makes the sort case-insensitive, grouping 'H' with 'h' and 'W' with 'w'.
- The most important thing to remember is that the
keyonly influences the sorting order. The original characters, with their original casing, are what you get in the final string.
Sorting with custom ordering using lambda functions
text = "a1b2c3"
# Sort with priority: digits first, then letters
custom_sorted = ''.join(sorted(text, key=lambda x: (not x.isdigit(), x)))
print(custom_sorted)--OUTPUT--123abc
For more complex sorting, you can pass a lambda function to the key parameter. In this case, the key lambda x: (not x.isdigit(), x) sorts digits before letters by returning a tuple that Python uses to determine the order.
- The first part of the tuple,
not x.isdigit(), evaluates toFalsefor digits andTruefor letters. Since Python sortsFalsebeforeTrue, all digits are placed first. - The second part,
x, is the character itself. It acts as a tie-breaker, sorting the digits and letters alphabetically within their respective groups.
Sorting vowels before consonants using custom functions
text = "python"
# Sort with priority: vowels first, then consonants
vowels_first = ''.join(sorted(text, key=lambda x: (0 if x.lower() in 'aeiou' else 1, x)))
print(vowels_first)--OUTPUT--ohnpty
This approach also uses a lambda function to define a custom sort order based on a tuple. Python sorts by the first element of the tuple, then uses the second element to break any ties.
- The logic
0 if x.lower() in 'aeiou' else 1assigns a priority number to each character. Since0comes before1, all vowels are grouped at the beginning of the sorted output. - The second part of the tuple,
x, is the character itself. It acts as a secondary sort, arranging the characters alphabetically within their respective vowel and consonant groups.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications faster.
With Agent 4, you can describe the app you want to build, and it will take your idea to a working product. Agent handles writing the code, connecting to APIs, and deploying it for you. Here are a few examples of tools you could build using the sorting logic from this article:
- An anagram solver that checks if two words are anagrams by sorting and comparing their characters.
- A data sanitizer that creates consistent IDs by sorting alphanumeric characters according to custom rules, like placing all digits first using a
lambdafunction. - A tag organizer that sorts user-generated tags case-insensitively with
key=str.lowerto prevent duplicates.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While sorting strings is usually straightforward, you might run into a few common issues with mixed data types, whitespace, and inconsistent casing.
A TypeError is a frequent error that occurs when you try to use sorted() on a collection containing incompatible data types, like numbers and strings. Python doesn’t know how to compare an integer to a letter, so it raises an error. To avoid this, ensure all items are of a comparable type before sorting, such as by converting all elements to strings.
Whitespace can also lead to unexpected results. Since spaces, tabs, and newlines are treated as characters, they are included in the sort and typically appear before letters and numbers. If you want to ignore them, you’ll need to remove them from the string before you sort it.
Finally, inconsistent sorting with mixed-case strings is a common challenge. By default, Python sorts all uppercase letters before any lowercase ones, meaning 'Z' comes before 'a'. If you need a true alphabetical sort, you can make the operation case-insensitive by using the key=str.lower parameter, which evaluates each character by its lowercase equivalent for ordering purposes.
Handling TypeError when sorting mixed types with sorted()
You'll hit a TypeError if you try to sort a collection containing incompatible types, like strings and numbers. Python can't compare 'a' to 1, so the operation fails. See what happens when you concatenate a string with a list of numbers and pass it to sorted().
numbers = [1, 2, 3]
text = "abc"
combined = sorted(text + numbers) # Will cause TypeError
print(''.join(combined))
The TypeError happens because the + operator can't concatenate a string with a list. This operation fails before sorted() even runs. To resolve this, you must convert all items to a single type. See the corrected approach below.
numbers = [1, 2, 3]
text = "abc"
combined = sorted(text + ''.join(map(str, numbers)))
print(''.join(combined))
The fix is to convert all numbers to strings before sorting. The map(str, numbers) function applies the str() conversion to each number, and ''.join() combines them into a single string. This lets you safely concatenate it with the original text using the + operator. The sorted() function can then process the unified string without a TypeError. Keep an eye out for this when combining data from different sources, like files or APIs.
Dealing with whitespace in string sorting
Sorting a string with whitespace can produce unexpected results. The sorted() function treats spaces as characters to be sorted, and since they come before letters in standard character order, they'll move to the front. See what happens in the example below.
text = "hello world"
sorted_text = ''.join(sorted(text))
print(sorted_text) # Space appears first in the sorted result
The output places the space first because sorted() treats it as a character with a lower value than any letter. This moves it to the front of the sequence. The following example shows how to get around this.
text = "hello world"
sorted_text = ''.join(sorted(text.replace(" ", "")))
print(sorted_text) # Sorts without spaces
The solution is to remove the whitespace before sorting. By calling text.replace(" ", ""), you create a new string that has no spaces. The sorted() function then operates on this clean string, ordering only the letters. Finally, ''.join() assembles the characters back into the final result. This is a simple way to ensure that spaces don't affect your alphabetical sorting, which is especially helpful when processing user input or text from files.
Correcting inconsistent sort order with mixed case strings
Python's default sorting behavior can be a surprise. It sorts all uppercase letters before any lowercase ones, which means 'Z' comes before 'a'. This can lead to results that don't look truly alphabetical. See what happens in the example below.
text = "aBcDeFg"
sorted_text = ''.join(sorted(text))
print(sorted_text) # Uppercase letters come before lowercase
The output groups all uppercase letters first because sorted() orders characters by their code point values, where B is less than a. The following example demonstrates how to achieve a proper alphabetical sort regardless of case.
text = "aBcDeFg"
sorted_text = ''.join(sorted(text, key=str.lower))
print(sorted_text) # Sorts ignoring case differences
The solution is to use the key parameter in the sorted() function. By setting key=str.lower, you’re telling Python to evaluate each character's lowercase version for sorting purposes, which ensures a true alphabetical order. The original character casing is preserved in the final output. This technique is essential when you need consistent sorting for user-generated content or data from external sources where capitalization can be unpredictable.
Real-world applications
Beyond debugging common errors, these sorting techniques are the foundation for building practical tools like anagram solvers and data grouping utilities with vibe coding.
Creating anagrams with sorted() and join()
A classic application for the sorted() and join() pattern is checking for anagrams, since two words are anagrams if their sorted characters form the exact same string.
def is_anagram(word1, word2):
return ''.join(sorted(word1.lower())) == ''.join(sorted(word2.lower()))
print(is_anagram("listen", "silent"))
print(is_anagram("heart", "earth"))
print(is_anagram("python", "java"))
This function determines if two words are anagrams by transforming them into a canonical form. First, it uses .lower() to handle case differences, ensuring 'Listen' and 'silent' are treated the same. Then, it applies a two-step process to each word:
sorted()rearranges the characters into alphabetical order.''.join()stitches them back into a single string.
The function's return value comes from comparing these two newly formed strings. An exact match with == means the original words are anagrams.
Grouping words by their sorted characters
You can also use this sorting pattern to categorize an entire list of words, grouping anagrams by using their shared sorted form as a dictionary key.
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
anagram_groups = {}
for word in words:
sorted_word = ''.join(sorted(word))
if sorted_word in anagram_groups:
anagram_groups[sorted_word].append(word)
else:
anagram_groups[sorted_word] = [word]
for group in anagram_groups.values():
print(group)
This script identifies anagrams by creating a common identifier for words with the same letters. It processes each word in the list, sorting its characters to form a new string like aet from eat. This sorted string serves as a unique key inside the anagram_groups dictionary.
- The code checks if a key already exists. If so, it appends the current
wordto the corresponding list. - If not, it initializes a new list for that key.
Finally, it iterates through the dictionary's values to print each collected group of anagrams.
Get started with Replit
Now, turn these sorting techniques into a real tool. Describe what you want to build to Replit Agent, like “build an anagram solver” or “create a tool to sort a list of tags alphabetically, ignoring case”.
Replit Agent handles writing the code, testing for errors, and deploying the app. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



