In Python, you can sort characters in a string using the sorted()
function.
In this example,
str
.sorted()
function to sort the characters in the string in ascending order.join()
method.str = 'hello world'
sorted_str = ''.join(sorted(str))
print('Sorted string in ascending order:', sorted_str)
Sorted string in ascending order: dehllloorw
In this example,
str
.sorted()
function with reverse=True
parameter to sort the characters in the string in descending order.join()
method.str = 'hello world'
sorted_str = ''.join(sorted(str, reverse=True))
print('Sorted string in descending order:', sorted_str)
Sorted string in descending order: wroolllhed
In this tutorial, we learned How to Sort Characters in String in Python language with well detailed examples.