Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort the letters in a string alphabetically in Python?
Sorting the letters in a string alphabetically is a common task in Python that helps with string manipulation and text analysis. It's useful for creating anagrams, checking for permutations, or standardizing input for consistent processing, for example, turning 'banana' into 'aaabnn'.
In this article, we will explore different approaches to sort the letters in a string alphabetically using Python's built-in functions.
Using Python sorted() Function
The Python sorted() function returns a new sorted list from the items in an iterable object. When applied to strings, it treats each character as a separate element and sorts them alphabetically.
Syntax
sorted(iterable, key=key, reverse=reverse)
Basic Example
Here's how to sort letters in a string using the sorted() function ?
text = "tutorialspoint" result = ''.join(sorted(text)) print(result)
aiilnooprstttu
Handling Mixed Case
When sorting strings with uppercase and lowercase letters, Python uses ASCII values. Uppercase letters have lower ASCII values and appear first ?
text = "WelcoMe" result = ''.join(sorted(text)) print(result)
MWceelo
For case-insensitive sorting, use the key parameter ?
text = "WelcoMe" result = ''.join(sorted(text, key=str.lower)) print(result)
ceelMoW
Handling Spaces and Special Characters
Spaces and special characters are sorted based on their ASCII values, appearing before letters ?
text = "Hi Hello"
result = ''.join(sorted(text))
print(f"'{result}'")
' HHeillo'
Using sorted() with Sets for Unique Characters
To sort a string and keep only unique characters, combine sorted() with set() ?
text = "TutorialsPoint" result = ''.join(sorted(set(text))) print(result)
PTailnorstu
Sorting in Descending Order
Use the reverse parameter to sort letters in descending order ?
text = "python" result = ''.join(sorted(text, reverse=True)) print(result)
ytonhp
Comparison of Methods
| Method | Use Case | Example Result |
|---|---|---|
sorted(text) |
Basic alphabetical sorting | 'banana' ? 'aaabnn' |
sorted(text, key=str.lower) |
Case-insensitive sorting | 'BaNaNa' ? 'aaBNnn' |
sorted(set(text)) |
Unique characters only | 'banana' ? 'abn' |
sorted(text, reverse=True) |
Descending order | 'banana' ? 'nnbaaa' |
Conclusion
The sorted() function is the most efficient way to sort letters in a string alphabetically. Use key=str.lower for case-insensitive sorting and combine with set() to get unique characters only.
