You are currently viewing How to Sort String in Python

How to Sort String in Python

Sorting strings is a common operation in Python. There are a number of ways to sort strings in Python. The easiest way to sort string in python is to use the sorted function. This function will take a string and return a new string that is sorted alphabetically.

We will go over three examples for sorting the string in this post. First, we will apply the sorting function to the string using sorted(string). It will return the sorted list of characters. Next, we will rejoin these characters and create a new string.

Example 1:

str = "AiOcta"
sorted_string = sorted(str)
print(sorted_string)
print(''.join(sorted_string))

Output:

['A', 'O', 'a', 'c', 'i', 't']
AOacit

Note: You can notice that in this example, the sorted function sorts the capitalized characters at the beginning of the list and creates a new string from AiOcta to AOacit.

Example 2:

str = "AiOcta"
lower_str = str.lower()
sorted_string = sorted(lower_str)
print(sorted_string)
print(''.join(sorted_string))

Output:

['a', 'a', 'c', 'i', 'o', 't']
aaciot

Note: To sort string in python alphabetically without considering capitalization, you must convert all the strings to lower case before sorting.

Example 3:

str = "AiOcta"
sorted_string = sorted(str, reverse=True)
print(sorted_string)
print(''.join(sorted_string))

Output:

['t', 'i', 'c', 'a', 'O', 'A']
ticaOA

Note: By using the parameter “reverse=True” in the sorted() function, you can sort the string in reverse order.

References:

https://docs.python.org/3/

Leave a Reply