How to sort the letters in a string alphabetically in Python?

PythonServer Side ProgrammingProgramming

To sort letters in a string alphabetically, you need to use the sorted function that returns a sorted list of letters which you can then join to get a string. For example,

>>> s = "helloworld"
>>> ''.join(sorted(s))
'dehllloorw'

If you want only unique characters sorted, you can use sets to get the result. For example,

>>> s = "helloworld"
>>> ''.join(sorted(set(s)))
'dehlorw'
raja
Published on 18-Dec-2017 11:24:32
Advertisements