Sort Characters in String
Python - Sort Characters in String
String is a sequence of characters. We can sort these characters in ascending or descending order.
The steps to sort characters in String are:
- Take a string.
- Sort the characters using sorted() function.
- Join the sorted characters into a string using str.join().
The other way of doing this is
- Take a string.
- Convert string to list of characters.
- Sort the characters using list.sort() method.
- Join the sorted characters into a string str.join().
In this tutorial, we will go through examples demonstrating the above two processes.
Examples
1. Sort characters in string using sorted()
In this example, we will take a string and sort the characters in it using sorted(). We will use str.join() method to join the sorted characters.
Python Examples
string = 'apple'
sorted_chars = sorted(string)
sorted_string = ''.join(sorted_chars)
print(sorted_string)Output
aelppTo sort the characters in descending order, you have have to provide True as argument for the named parameter reverse of sorted() function, as shown below.
Python Examples
string = 'apple'
sorted_chars = sorted(string, reverse=True)
sorted_string = ''.join(sorted_chars)
print(sorted_string)Output
pplea2. Sort characters in given string using list.sort()
In this example, we will take a string and sort the characters in it using list.sort() method. We will use str.join() method to join the sorted characters.
Python Examples
string = 'apple'
chars = list(string)
chars.sort()
sorted_string = ''.join(chars)
print(sorted_string)Output
aelppThe string is sorted in ascending order, which is the default order. You can sort the string in descending order using list.sort(reverse = True) as shown below.
Python Examples
string = 'apple'
chars = list(string)
chars.sort(reverse = True)
sorted_string = ''.join(chars)
print(sorted_string)Output
ppleaSummary
In this tutorial of Python Examples, we learned how to sort characters in a string using list.sort() method and sorted() built-in function.