Computer >> Computer tutorials >  >> Programming >> Python

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


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'