How to sort the letters in a string alphabetically in Python
Is there an easy way to sort the letters in a string alphabetically in Python?
So for:
a = 'ZENOVW'
I would like to return:
'ENOVWZ'
Solution 1:
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
Solution 2:
>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']
sorted
returns a list, so you can make it a string again using join
:
>>> c = ''.join(b)
which joins the items of b
together with an empty string ''
in between each item.
>>> print c
'ENOVWZ'