How to Sort a String in Python?
The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally need to sort data based on a customer name in ascending or descending order, Python provides the sort methods for this purpose. Sorting strings has always been a very common utility with many applications worldwide. Containers can be sorted in Python using the two methods, sort() and sorted().
The sorted() method creates a new sorted list from an original list, whereas the sort() method adjusts the list while it is already in place.
Python sort string sorted() function syntax:
sorted(iterable, key = key, reverse = reverse)
Parameters:
- Iterable: This is a list of strings that must be sorted; it is not an optional argument.
- Key: This parameter can provide the functionality to execute to select the sort order. None is the default value.
- Reverse: The Boolean argument specifies whether the order should be ascending or descending. False indicates descending order, while True indicates ascending order. Here, False is the default setting.
Value Returned:
This method returns a sorted string as its result.
Python's sort string functionality
Python's sort string function accepts a string as a parameter, compares each character in the string based on its ASCII value, and then returns a list of the string's sorted characters.
Python examples of sorting strings
The suggested instances are shown below:
Example 1: Use Python's built-in sorted() method to sort a string.
# making a string
msg = "Hello!, how are you"
print("The original message is : ")
print(msg)
# getting a list of sorted characters using the sorted() method
alt_msg = sorted(msg)
print( "The output of the sorted() method is : " )
print( alt_msg )
# getting a list of sorted characters using the sorted() method
sort_msg = "".join(alt_msg)
print( "The sorted message is : " )
print( sort_msg )
Output:
The original message is:
Hello! how are you
The output of the sorted() method is:
[', '', '', ''!', ', ''H,' 'a', 'e,' 'e,' 'h,' 'l,' 'l,' 'o', 'o', 'o', 'r,' 'u,' 'w,' 'y']
The sorted message is:
!,Haeehlloooruwy
The same string variable that stores the "Hello! how are you" is generated in the program. The sorted() method, which returns a sorted list of string characters, is then used in the program (as displayed in the output). The join() method returns the string of sorted characters and is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order. Because the space character's ASCII value is lower than all the other characters in the string, it is the first character in the sorted string.
Example 2: A Python while loop is used to sort a string.
# making a string
string = "Sample string to sort alphabetical order."
print( "The original string is : " )
print( string )
# getting a list of sorted characters in ascending order using the sorted() function
list_string=list( string )
print( "The list of string is : " )
print( list_string )
list_string = list(string)
i = 0
while i < len( list_string ):
key = i
j = i+1
while j < len( list_string ):
if list_string[key] > list_string[j]:
key = j
j += 1
list_string[i],list_string[key] = list_string[key],list_string[i]
i += 1
print( "The list of sorted string is : " )
print( list_string )
new_string = "".join(list_string )
print( "The sorted string is : " )
print(new_string)
Output:
The original string is:
Sample string to sort in alphabetical order:
The list of the string is as follows:
[‘s’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, ‘ ‘, ‘s’, ‘t’, ‘r’, ‘I’, ‘n’, ‘g’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘s’, ‘o’, ‘r’, ‘t’, ‘ ‘, ‘a’, ‘l’, ‘p’, ‘h’, ‘a’, ‘b’, ‘e’, ‘t’, ‘I’, ‘c’, ‘a’, ‘l’, ‘ ‘, ‘o’, ‘r’, ‘d’, ‘e’, ‘r’, ‘.’]
The last sorted string is:
[‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘, ‘ .’, ‘ s ‘, ‘ a ‘, ‘ a ‘, ‘ b ‘, ‘ c ‘, ‘ d ‘, ‘ e ‘, ‘ e ‘, ‘ e ‘, ‘ g ‘,
' h, '' I, '' I, '' l, '' l, '' m, '' n, '' o, '' o ', ' o ', ' p ', ' p ', ' r ', ' r ‘, ‘ s ‘, ‘ s ‘, ‘ t ‘, ‘ t ‘, ‘ t ‘, ‘ t ‘ ]
The sorted string is:
.Saaaabcdeeeghiilllmnooopprrrrsstttt
The phrase "Sample string to sort alphabetically" appears in the abovementioned program. Without utilising the sorted() method, is sorting. Similar to the program above, which compares each character using a while loop, the first while loop ensures that the loop iteration should be smaller than the length of the string before taking each element in turn and comparing and swapping them in the second while loop. Therefore, a sorted list of string characters is returned. The join() method is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order.
Example 3: Show how to build bubble sort in Python by using a “for loop” to sort a text.
# making a string
string = "This is a sample string"
new_string = []
print( "The original string is : " )
print( string )
# To obtain a list of sorted characters without using the sorted() function
list_string=list(string)
print( "The list of string is : " )
print(list_string)
list_string=list(string)
len_s=len(list_string)
for i in range(len_s-1):
for j in range(len_s-i-1):
if list_string[j]>list_string[j+1]:
list_string[j],list_string[j+1]=list_string[j+1],list_string[j]
For m in list_string:
new_string+=m
print( "The list of sorted string is : " )
print(new_string)
sort_string = "".join(new_string)
print( "The sorted string is : " )
print(sort_string)
Output:
The original string is :
This is a sample string
The list of the string is as follows:
[‘T’, ‘h’, ‘I’, ‘s’, ‘ ‘, ‘I’, ‘s’, ‘ ‘, ‘I’, ‘s’, ‘ ‘, ‘a’, ‘ ‘, ‘s’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’, ‘ ‘, ‘s’, ‘t’, ‘r’, ‘I’, ‘n’, ‘g’]
The list of the sorted string is as follows:
[‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘, ‘T’, ‘a’,‘a’, ‘e’, ‘g’, ‘h’, ‘i’, ‘i’, ‘i’, ‘l’, ‘m’, ‘n’, ‘p’, ‘r’, ‘s’, ‘s’, ‘s’, ‘s’ ‘t’]
The sorted string is:
Taaeghiiilmnprsssst
The string "This is a sample string" is sorted similarly to the program above without using the sorted() method. The program uses a “for loop” to compare each character. If the previous character is greater than the following character, a swap is made; otherwise, there is no swap. Consequently, it provides a sorted list of string characters (as displayed in the output). The join() method, which returns an ascending string, is then used to join the sorted list of characters. As a result, the final sorted string still contains all the characters from the original string but in a different order.
Sorting a string with sorted() + reduce() + lambda
When reducing an iterable to a single cumulative value after applying a function to it, the reduce() method is useful. The function defined in Python without a name is called a lambda function.
Combine the sorted(), reduce(), and lambda functions to sort a text alphabetically. Reduce() is not a built-in function in Python. Therefore, we must import the fun tools package containing the reduce() function.
Example:
import functools
data = "immunoelectrophoretically"
print("The original string is : " + str(data))
sorted string = functools.reduce(lambda x, y: x + y, sorted(data))
print("String after sorting : " + str(sortedString))
Output:
The original string is: immunoelectrophoretically
String after sorting: acceeehiilllmmnoooprrttuy
Python reverse string sorting instructions
Use the sorted() and join() functions in Python and supply the reverse = True option to the sorted() function to sort a string in reverse order.
Example:
data = "immunoelectrophoretically"
print("The original string is : " + str(data))
reverse sorted = ''.join(sorted(data, reverse = True))
print("The reverse sorted string: ",reverse sorted)
Output:
The original string is: immunoelectrophoretically
The reverse sorted string: yuttrrpooonmmllliiheeecca
You can see that it gave back a reverse-sorted string in the output.