0
0
PythonProgramBeginner · 2 min read

Python Program to Sort Characters in String

You can sort characters in a string in Python by using ''.join(sorted(your_string)), which sorts the characters and joins them back into a string.
📋

Examples

Inputstring
Outputginrst
Inputhello
Outputehllo
Input
Output
🧠

How to Think About It

To sort characters in a string, think of the string as a list of letters. You want to arrange these letters in order from smallest to largest based on their Unicode values. You can split the string into characters, sort them, and then join them back together.
📐

Algorithm

1
Get the input string.
2
Convert the string into a list of characters.
3
Sort the list of characters in ascending order.
4
Join the sorted characters back into a single string.
5
Return or print the sorted string.
💻

Code

python
input_str = input("Enter a string: ")
sorted_str = ''.join(sorted(input_str))
print(sorted_str)
Output
ehllo
🔍

Dry Run

Let's trace the input 'hello' through the code

1

Input string

input_str = 'hello'

2

Sort characters

sorted(input_str) = ['e', 'h', 'l', 'l', 'o']

3

Join characters

''.join(['e', 'h', 'l', 'l', 'o']) = 'ehllo'

4

Print result

Output: 'ehllo'

StepCharacters
Originalh, e, l, l, o
Sortede, h, l, l, o
💡

Why This Works

Step 1: Sorting characters

The sorted() function breaks the string into characters and sorts them by their Unicode values.

Step 2: Joining characters

The ''.join() method combines the sorted list of characters back into a single string.

🔄

Alternative Approaches

Using list and sort() method
python
input_str = input("Enter a string: ")
char_list = list(input_str)
char_list.sort()
sorted_str = ''.join(char_list)
print(sorted_str)
This method sorts the list in place and then joins it; it is slightly more verbose but clear.
Using sorted() with reverse=True
python
input_str = input("Enter a string: ")
sorted_str = ''.join(sorted(input_str, reverse=True))
print(sorted_str)
Sorts characters in descending order instead of ascending.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting characters takes O(n log n) time where n is the length of the string because sorting algorithms like Timsort are used.

Space Complexity

Extra space O(n) is used to store the sorted list of characters before joining them back.

Which Approach is Fastest?

Using sorted() is efficient and concise; using list.sort() is similar but modifies the list in place.

ApproachTimeSpaceBest For
sorted() with joinO(n log n)O(n)Simple and readable code
list.sort() with joinO(n log n)O(n)In-place sorting with explicit list
sorted() with reverse=TrueO(n log n)O(n)Sorting in descending order
💡
Use sorted() with ''.join() to easily sort characters in a string.
⚠️
Trying to sort the string directly without converting it to a list or using sorted() which returns a list.