engineering

How to Sort a String in Python: A Practical Guide

Sorting strings in Python is a common task whether you are organizing names, normalizing input, or preparing data for comparison. Python provides built-in tools that make string...

Mara Ellison
How to Sort a String in Python: A Practical Guide

Sorting strings in Python is a common task whether you are organizing names, normalizing input, or preparing data for comparison. Python provides built-in tools that make string sorting straightforward, while also giving you control over ordering rules, case sensitivity, and locale-specific behavior. This guide explains the core functions, practical patterns, and edge cases you will use most often when sorting strings in real projects.

How Python Handles Sorting

At the core, Python relies on two functions and methods to arrange sequences:

  • sorted(iterable, key=None, reverse=False) returns a new sorted list from any iterable.
  • list.sort(key=None, reverse=False) sorts a list in-place and returns None.

Both accept optional arguments that control ordering through the key function and direction through the reverse flag. Strings are iterable sequences of characters, so sorting a string typically means turning it into a list of its characters or substrings and then applying one of these tools.

Sort Characters in a String Alphabetically

The simplest way to sort the characters in a string is to pass it to sorted(), which returns a list of characters in ascending order based on Unicode code points. For basic ASCII text, this corresponds to alphabetical order for letters and numeric order for digits.

>>> text = 'python'
>>> sorted(text)
['h', 'n', 'o', 'p', 't', 'y']

From Sorted List Back to String

Because sorted() returns a list, you often need to recombine characters into a string. Use ''.join(sorted(text)) to produce a sorted string directly.

>>> ''.join(sorted('python'))
'hnopty'

Sort in Reverse and Slice for Subsets

Set reverse=True to get descending order, and combine sorted() with slicing to extract subsets such as the smallest or largest characters.

>>> text = 'python'
>>> ''.join(sorted(text, reverse=True))
'ytonph'
>>> ''.join(sorted(text))[:3]
'hno'

Custom Ordering with the Key Function

The key argument is essential when you need case-insensitive sorting, numeric ordering embedded in strings, or other non-default rules. The key function transforms each element before comparisons but returns the original elements in the new order.

Case-Insensitive Sorting

Use str.lower to ignore case while preserving original casing in the output.

>>> items = ['Banana', 'apple', 'Cherry']
>>> sorted(items, key=str.lower)
['apple', 'Banana', 'Cherry']

Sort by Length or Other Attributes

Sort strings by their length by passing key=len.

>>> items = ['pear', 'fig', 'banana']
>>> sorted(items, key=len)
['fig', 'pear', 'banana']

Sort Lists and Arrays of Strings

When working with multiple strings, use list.sort() to reorder in-place or sorted() to create a new list.

>>> items = ['banana', 'Apple', 'cherry']
>>> sorted(items, key=str.lower)
['Apple', 'banana', 'cherry']
>>> items.sort(key=str.lower)
>>> items
['Apple', 'banana', 'cherry']

Locale-Aware Sorting for Correct Cultural Ordering

For user-facing lists that must follow language-specific rules, use locale.strxfrm in Python 3 and the locale module. This ensures accented characters and language-specific ordering behave as expected. On some platforms, you must set the locale explicitly before using it.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')  # use system default locale
'pt_BR.UTF-8'
>>> items = ['casa', 'Árvore', 'banana']
>>> sorted(items, key=locale.strxfrm)
['Árvore', 'banana', 'casa']

Note: locale-aware sorting may raise errors if the requested locale is not available on your system. Always handle exceptions or validate locale availability in production code.

Comparison of Common Sorting Patterns

Goal Approach Result Example (input: 'Python')
Alphabetical (default) ''.join(sorted('Python')) 'Phnoty'
Reverse alphabetical ''.join(sorted('Python', reverse=True)) 'ytonhP'
Case-insensitive sorted(['Banana','apple'], key=str.lower) ['apple', 'Banana']
By string length sorted(['pear','fig'], key=len) ['fig', 'pear']
Locale-aware sorted(items, key=locale.strxfrm) Language-specific order

Performance and Practical Considerations

Python’s sort is stable and uses Timsort with O(n log n) complexity, which is efficient for most workloads. For very large lists of strings, the cost of the key function is multiplied by the number of comparisons, so keep key logic lightweight. Reusing a computed key with decorators like sorted((s.lower(), s) for s in strings) can reduce repeated work in complex scenarios.

Common Pitfalls and Fixes

  • Accents and case mismatches: Default sorting is based on Unicode code points, so uppercase letters may sort before lowercase, and accented characters may appear in unexpected positions. Use key=str.lower and locale-aware transforms where appropriate.
  • In-place mutation: list.sort() modifies the original list and returns None; using it by mistake can lead to lost data.
  • Encoding assumptions: When sorting byte strings (bytes), ordering is by integer values of bytes. Decode to text for language-aware behavior unless you explicitly need byte-level ordering.

Related Reading

More pages in this topic cluster.

Dark Black Bug: what it is, causes, and safe fixes

A dark black bug most often refers to a visual rendering issue where a UI element, pixel, or overlay appears as a nearly opaque black block that resembles a bug or artifact. In...

Read next
Branch Circuit Example: A Clear, Practical Walkthrough

A branch circuit is the wiring path from a circuit breaker to the outlets and fixtures served by it. In this branch circuit example, a 20A dedicated circuit supplies power to a...

Read next
I Beam Load Capacity: What It Means and How It Is Determined

An i beam load capacity is the maximum load a steel I beam can safely support while staying within acceptable deflection and stress limits. This capacity depends on the beam’s...

Read next