How to sort a string in Python

Learn how to sort a string in Python. Discover different methods, tips, real-world applications, and how to debug common sorting errors.

How to sort a string in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

To sort a string in Python is a common task for data manipulation and algorithmic challenges. Since strings are immutable, you must use specific functions to handle the character sequence correctly.

You'll learn the main techniques with sorted() and .join(), along with performance tips. You will also discover real-world uses and find solutions for common errors.

Using sorted() and join() to sort a string

text = "python"
sorted_text = ''.join(sorted(text))
print(sorted_text)--OUTPUT--hnopty

This approach is a classic Pythonic solution that works around the fact that strings are immutable. You can't alter a string in place, so you need to create a new one. The process involves two key steps:

  • First, the sorted() function takes the string and returns a new list with the characters sorted alphabetically, like ['h', 'n', 'o', 'p', 't', 'y'].
  • Then, the .join() method is called on an empty string '' to concatenate the elements of that list, effectively building the final sorted string.

Basic string sorting techniques

You can expand on this technique by converting to a list(), using the reverse parameter, or filtering characters before joining them back into a string.

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

This method offers a more explicit alternative to using sorted(). By first converting the string to a list, you create a mutable sequence that you can directly manipulate.

  • The list() function breaks the string into a list of its characters.
  • Then, the list’s sort() method rearranges the characters in place. This method modifies the list itself and returns None.
  • Finally, ''.join() is used to combine the sorted characters back into a single 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

To sort a string in descending order, you just need to add an argument to the sorted() function. This approach builds directly on the standard method you've already seen.

  • The key is the reverse=True parameter. It tells the function to arrange the characters from Z to A instead of the default A to Z.
  • After sorting, ''.join() stitches the reversed list of characters back into a string.

It’s a simple tweak that gives you control over the sort direction without needing extra steps or more complex logic.

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

Sometimes you only want to sort specific characters in a string. List comprehension offers a compact way to filter out unwanted characters before sorting. This technique lets you build a new list based on specific criteria in a single, readable line.

  • The expression [c for c in text if c.isalpha()] creates a list containing only the letters from the original string.
  • The if c.isalpha() clause acts as a filter, checking each character and discarding any that aren't alphabetic, like numbers or symbols.
  • Once you have this filtered list, you sort and join it as you've seen before.

Advanced string sorting techniques

Building on the basic methods, you can tackle more advanced sorting challenges by providing a custom key to define exactly how characters should be ordered.

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, sorting is case-sensitive, which means uppercase letters are ordered before their lowercase counterparts. The key parameter in the sorted() function provides a way to customize this logic without altering the original data.

  • Setting key=str.lower tells the function to use the lowercase version of each character for comparison purposes only.
  • This ensures that characters like 'H' and 'h' are treated equally during the sort, leading to a true alphabetical order.
  • The original case of the characters is preserved in the final output 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 complex sorting rules, you can pass a lambda function to the key parameter. This example prioritizes digits over letters by having the lambda return a tuple. Python sorts items based on the first element of the tuple, then uses subsequent elements to break ties.

  • The expression lambda x: (not x.isdigit(), x) generates a tuple for each character. The first value is False for digits and True for letters.
  • Because False is sorted before True, all digits come first.
  • The character x itself is the second item in the tuple, ensuring that characters within each group—digits or letters—are sorted correctly.

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

You can create even more specific sorting rules by using a tuple in a lambda function. This technique lets you group characters before sorting them alphabetically.

  • The key lambda x: (0 if x.lower() in 'aeiou' else 1, x) assigns a tuple to each character. Vowels get a 0 and consonants get a 1 as their first tuple element.
  • Since Python sorts tuples element by element, all vowels (group 0) come before consonants (group 1). The second element, x, sorts the characters alphabetically within their respective groups.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the string sorting techniques we've explored, Replit Agent can turn them into production-ready tools:

  • Build an anagram finder that takes a word and generates all valid anagrams from a dictionary.
  • Create a custom text formatter that sorts characters based on rules like case-insensitivity or prioritizing numbers over letters.
  • Deploy a data canonicalization API that standardizes identifiers by sorting their characters alphabetically.

You can take any of these concepts, describe them in plain English, and let Replit Agent handle the coding, testing, and deployment for you, right in your browser.

Common errors and challenges

While sorting strings is often straightforward, you can encounter issues with mixed data types, whitespace, and inconsistent casing that require specific solutions.

Handling TypeError when sorting mixed types with sorted()

You'll hit a TypeError if you try to use sorted() on a list containing incompatible data types, like numbers and strings. Python doesn't know how to natively compare 'a' and 1, so it raises an error. To fix this, you must ensure all elements are of the same type before sorting. You can either filter the list to include only one type or convert all elements to strings using a list comprehension like [str(x) for x in my_list].

Dealing with whitespace in string sorting

Whitespace characters aren't ignored during sorting. In fact, characters like spaces, tabs, and newlines have their own positions in the character order, typically appearing before any letters or numbers. If your goal is to sort only the visible characters, you should first remove the whitespace. You can use methods like .strip() to remove leading or trailing spaces or filter them out entirely before passing the string to sorted().

Correcting inconsistent sort order with mixed case strings

A common surprise is seeing uppercase letters sorted before lowercase ones, like 'Z' coming before 'a'. This happens because default sorting relies on character codes where uppercase letters have lower values. This can lead to results that don't look truly alphabetical. As shown earlier, the solution is to provide a key to the sorted() function, such as str.lower, to normalize the case for comparison and achieve a natural, case-insensitive order.

Handling TypeError when sorting mixed types with sorted()

You'll trigger a TypeError if you try to sort a list containing incompatible data types, such as strings and integers. Python can't natively compare them, so it raises an error. The following code demonstrates what happens when you attempt this combination.

numbers = [1, 2, 3]
text = "abc"
combined = sorted(text + numbers) # Will cause TypeError
print(''.join(combined))

The TypeError is triggered because the + operator can't concatenate a string with a list. The operation fails before sorted() even runs. The following example shows the correct way to prepare the data for sorting.

numbers = [1, 2, 3]
text = "abc"
combined = sorted(text + ''.join(map(str, numbers)))
print(''.join(combined))

To fix the TypeError, you must convert all items to a single type before sorting. The solution uses map(str, numbers) to turn each integer into a string. Then, ''.join() combines these into a single string like '123'.

This new string can be safely concatenated with the original text using the + operator, making the combined data ready for sorted(). Keep an eye out for this error when combining data from different sources, like databases or APIs.

Dealing with whitespace in string sorting

It's easy to forget that whitespace is a character too. When you sort a string containing spaces, the sorted() function includes them in the operation, often placing them before any letters. This can disrupt your intended alphabetical order. See what happens below.

text = "hello world"
sorted_text = ''.join(sorted(text))
print(sorted_text) # Space appears first in the sorted result

The sorted() function treats the space in "hello world" as just another character. Since its character code comes before any letter, it gets placed at the front. The next example demonstrates how to correct this.

text = "hello world"
sorted_text = ''.join(sorted(text.replace(" ", "")))
print(sorted_text) # Sorts without spaces

To get a purely alphabetical sort, you must first remove the whitespace. The solution uses the replace(" ", "") method to create a new string without any spaces. When you pass this modified string to sorted(), the function only operates on the letters. This approach is ideal when you need to compare the content of strings while ignoring their original formatting or spacing.

Correcting inconsistent sort order with mixed case strings

It's a common surprise when sorting strings that uppercase letters appear before lowercase ones. This happens because sorted() defaults to character code order, not pure alphabetical logic. The code below demonstrates this behavior with a mixed-case string, showing the unexpected result.

text = "aBcDeFg"
sorted_text = ''.join(sorted(text))
print(sorted_text) # Uppercase letters come before lowercase

The sorted() function doesn't sort alphabetically as you might expect. It orders characters by their code points, meaning 'B' and 'D' come before 'a' and 'c'. The following example shows how to correct this behavior.

text = "aBcDeFg"
sorted_text = ''.join(sorted(text, key=str.lower))
print(sorted_text) # Sorts ignoring case differences

The solution is to pass the key=str.lower argument to the sorted() function. This tells the function to use the lowercase version of each character for comparison, so 'a' and 'A' are treated equally. The original case is preserved in the final output, giving you a true alphabetical order. This is especially useful when you're working with text from different sources or user input where casing can be inconsistent.

Real-world applications

Beyond fixing errors, sorting strings with sorted() and .join() unlocks powerful applications, from finding anagrams to grouping similar words.

Creating anagrams with sorted() and join()

The combination of sorted() and .join() is the key to identifying anagrams, as two words are anagrams only if their sorted character sequences are identical.

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"))

The is_anagram function checks if two words are anagrams by creating a unique signature for each. It’s a neat trick that relies on a simple principle: if two words have the same letters, their sorted versions will be identical.

  • First, it calls .lower() on each word to handle case-insensitivity.
  • Next, sorted() and ''.join() work together to create a new string with all characters sorted alphabetically.
  • Finally, it compares these two new strings. If they match, the function returns True.

Grouping words by their sorted characters

You can take this concept a step further by using the sorted string as a dictionary key to efficiently group all anagrams from a list of words.

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 cleverly organizes words into anagram groups. It iterates through the words list and generates a canonical form for each word by sorting its characters. For instance, both eat and tea produce aet.

  • It uses this sorted string to check the anagram_groups dictionary.
  • If a group for aet already exists, it appends the current word.
  • Otherwise, it starts a new group with the word.

The result is a dictionary where each value is a list of words that are anagrams of each other.

Get started with Replit

Turn what you've learned into a real tool. Describe your idea to Replit Agent, like "build a word jumble solver" or "create an API to canonicalize product IDs by sorting their characters."

Replit Agent writes the code, tests for errors, and deploys your app. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.