Search Authority

Sort a String in Python: Easy Guide & Code Examples

Sorting a string in Python is a common task when you need characters in alphabetical order, numeric sequence, or a custom pattern. The built-in tools make it straightforward to...

Mara Ellison
Sort a String in Python: Easy Guide & Code Examples

Sorting a string in Python is a common task when you need characters in alphabetical order, numeric sequence, or a custom pattern. The built-in tools make it straightforward to turn mixed text into a predictable, ordered representation.

Whether you are cleaning user input, preparing labels, or analyzing word frequencies, understanding how to sort a string python structure gives you precise control over text data.

Goal Method Result Type Mutability
Alphabetical order sorted(string) List of characters Immutable original
Reverse alphabetical sorted(string, reverse=True) List of characters Immutable original
Custom pattern sort sorted(string, key=custom_func) List of characters Immutable original
Rejoin to string "".join(sorted(string)) String New object

Basic Lexicographic Sorting

Lexicographic order arranges characters based on Unicode code points, which for letters means A-Z then a-z with consistent rules. Using sorted on a string returns a list where characters appear from lowest to highest code point value.

Case Sensitivity in Default Sort

Uppercase letters sort before lowercase letters in default lexicographic order, so "Zebra" would place "A" before "a". If you need case-insensitive results, you can supply a key that normalizes case before comparison.

Key Functions and Custom Sorting

The key parameter lets you define how each character is evaluated during the sort, enabling complex ordering rules without changing the original string. This is essential when you want numeric digits first, ignore accents, or apply domain-specific priorities.

Using Lambda for Inline Logic

With a lambda, you can map each character to a transformed value for comparison, such as lowercasing or mapping letters to positions in a custom alphabet. The original string remains unchanged, and you receive a new list reflecting your rules.

Rejoining to a Sorted String

Because sorted returns a list, you often join the result back into a string with "".join() to match typical string workflows. This pattern appears frequently in normalization tasks, anagram checks, and formatted output generation.

Handling Duplicates and Stability

Python sorting is stable, meaning that when multiple characters compare equal, their input order is preserved in the output list. For strings with repeated letters, this stability keeps behavior predictable and supports multi-stage sorting strategies.

Best Practices and Recommendations

  • Decide whether you need a list or a string, and join explicitly after sorting.
  • Use key functions to control ordering rules instead of altering the original text.
  • Remember that sorted always creates a new object, leaving the source string intact.
  • Test edge cases like mixed case, digits, and whitespace to ensure the output meets expectations.

FAQ

Reader questions

How do I sort a string in reverse alphabetical order?

Pass reverse=True to sorted, like "".join(sorted(your_string, reverse=True)), to get characters from Z to A.

Can I sort a string numerically if it contains digits?

Yes, use key=int inside sorted for digit characters, or a lambda that handles mixed content, to order positions as 0, 1, 2, and so on.

What happens to spaces and punctuation when sorting?

Spaces and punctuation are sorted by their Unicode values, typically before letters, which can affect readability if rejoining blindly.

How can I sort case-insensitively but preserve original case?

Use key=str.lower in sorted to compare lowercase versions while keeping the original characters in their given form.

Related Reading

More pages in this topic cluster.

Who Designed the Nike Logo? The Story Behind the Swoosh

The Nike swoosh is one of the most recognizable symbols in the world, but few people know the story behind its creation. This piece explores who designed the Nike logo, why it h...

Read next
What is the World's Hottest Pepper? 🌶️🔥

When people ask about the world's hottest pepper, they usually mean the variety that currently holds the Guinness World Record and pushes the boundaries of capsaicin heat. Peppe...

Read next
Jon Huertas in This Is Us:角色, 出演时期与剧情影响详解

Jon Huertas 在《这就是我们》中饰演成年 Kevin Pearson,这一角色从2016年首播持续至2022年最终季,构成了剧集核心家庭叙事的重要组成部�...

Read next