How to sort the letters in a string alphabetically in Python


Question

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'
1
134
2/23/2013 10:00:04 PM

Accepted Answer

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
236
2/23/2013 10:02:27 PM

>>> 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'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon