How to sort a string in Python? You can use various approaches in Python to sort the strings. Strings are immutable, which means you cannot modify the characters in place after creating a string. Due to their immutability, the built-in sort()(which is an in-place sorting method) method cannot be directly applied to strings. However, there are several ways to sort a string in Python using different approaches.
You can sort a string in Python using many ways, for example, by using join()
, sorted()
, reduce()
, lambda
, and for loop. In this article, I will explain how to sort a string by using all these functions with examples.
1. Quick Examples of Sorting a String
If you are in a hurry, below are some quick examples of sorting a string.
# Quick examples of sorting a string
# Initialize the string
string_to_sort = "sparkbyexamples"
# Example 1: Using join() and sorted() functions
sorted_string = ''.join(sorted(string_to_sort))
# Example 2: Using sorted(str, reverse = True)
sorted_string = ''.join(sorted(string_to_sort, reverse = True))
# Example 3: Using sorted(), reduce(), and lambda
sorted_string = reduce(lambda x, y: x + y, sorted(string_to_sort))
# Example 4: Using sorted(), reduce(), and lambda
# Initialize the string
string_to_sort = "SparkByExamples"
# Sorting a string in a case-insensitive manner
sorted_string = reduce(lambda x, y: x + y, sorted(string_to_sort, key=lambda x: x.lower()))
# Example 5: Using for loop
list1 = list(string_to_sort)
list1.sort()
for x in list1:
print(x, end = "")
2. Python String Sort Alphabetically
You can sort a string using the sorted() function along with the join() function in Python. For example, apply the sorted()
function over the given string string_to_sort
and then sort its characters alphabetically. Then, you can use the join()
method to concatenate this list of sorted characters back into a string.
# Initialize the string
string_to_sort = "sparkbyexamples"
print("Original string:",string_to_sort)
# Using sorted() with join()functions
# Sort a string
sorted_string = ''.join(sorted(string_to_sort))
print("After sorting a string:",sorted_string)
Yields below output.
3. Python String Sort in Reverse
Similarly, You can use the sorted() function along with the join() function to sort the string in reverse order. Pass the reverse parameter along with the given string into the sorted() function, it will return the list of sorted characters in reverse order. Then apply the join() function to the list of sorted characters, it will join it back to a string.
# Initialize the string
string_to_sort = "sparkbyexamples"
print("Original list:",string_to_sort)
# Sort a string in reverse order
sorted_string = ''.join(sorted(string_to_sort, reverse = True))
print("After sorting a string in reverse order:", sorted_string)
Yields below output.
4. Sort a String Using sorted() with reduce()
You can sort a string using the sorted()
function along with reduce() from the functools module and a lambda function.
In the below example, the sorted()
function sorts the characters in the string_to_sort
string in ascending order based on their ASCII values, considering the case. The reduce()
function then takes the sorted list of characters and concatenates them in the same order they appear in the sorted list, resulting in the string ‘aabeeklmpprssxy’.
from functools import reduce
# Initialize the string
string_to_sort = "sparkbyexamples"
print("Original string:",string_to_sort)
# Using sorted(), reduce(), and lambda
# Sorting a string
sorted_string = reduce(lambda x, y: x + y, sorted(string_to_sort))
print("After sorting a string:",sorted_string)
# Output:
Original string: sparkbyexamples
After sorting a string: aabeeklmpprssxy
If you want to sort the string in a case-insensitive manner, you can pass the lambda function key=lambda x: x.lower()
along with sorted()
function into reduce()
function. Now the string “SparkByExamples” is sorted in a case-insensitive manner, resulting in “aBEEklmprrSsyx”.
from functools import reduce
# Initialize the string
string_to_sort = "SparkByExamples"
print("Original string:",string_to_sort)
# Using sorted() + reduce() + lambda
# Sorting a string in a case-insensitive manner
sorted_string = reduce(lambda x, y: x + y, sorted(string_to_sort, key=lambda x: x.lower()))
print("After sorting a string:",sorted_string)
# Output:
# Original string: SparkByExamples
# After sorting a string: aaBEeklmpprSsxy
5. Sort a Python string using For Loop
You can use the for loop along with the sort() function to sort a string. In Python, the Sort() function can’t be used directly to strings, because strings are immutable. First, we need to convert the given string into a list and then apply the sort() function. It sorts the list in ascending order. Finally, use a for loop to iterate the sorted list and get them as a sorted string.
# Initialize the string
string_to_sort = "sparkbyexamples"
print("Original string:",string_to_sort)
list1 = list(string_to_sort)
list1.sort()
print("After sorting a string:")
for x in list1:
print(x, end = "")
# Output:
# Original string: sparkbyexamples
# After sorting a string:
# aabeeklmpprssxy
6. Conclusion
In this article, I have explained how to sort a string in Python by using join()
, sorted()
, reduce()
, lambda
, and for loop along with the sort() function with multiple examples. Also explained using the sorted() function with the join() function how we can sort the string in reversing order.
Happy Learning !!
Related Articles
- Python Convert String to Bytes
- Python Hex to String
- Python Join List to String by Delimiter
- Python String find() with Examples
- Python String Contains
- Python Remove Spaces From String
- Python String center() Method
- Python String count() Method
- Python String Unicode
- Python String Remove Numbers
- Python String Startswith
- Python String to Boolean
- Pad String with Spaces in Python
- Python Count Specific Character in String
- Python Convert String to Float
- Python Count Characters in String