Python – Sort Characters in String

Python – 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:

  1. Take a string.
  2. Sort the characters using sorted() function.
  3. Join the sorted characters into a string using str.join().

The other way of doing this is

  1. Take a string.
  2. Convert string to list of characters.
  3. Sort the characters using list.sort() method.
  4. 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)
Run Code Copy

Output

aelpp

To 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)
Run Code Copy

Output

pplea

2. 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)
Run Code Copy

Output

aelpp

The 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)
Run Code Copy

Output

pplea

Summary

In this tutorial of Python Examples, we learned how to sort characters in a string using list.sort() method and sorted() built-in function.

Related Tutorials

Code copied to clipboard successfully 👍