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'

7 Answers

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
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'

Sorted() solution can give you some unexpected results with other strings.

List of other solutions:

Sort letters and make them distinct:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.