219

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'
Superdooperhero
  • 7,584
  • 19
  • 83
  • 138

7 Answers7

369

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
K Z
  • 29,661
  • 8
  • 73
  • 78
111
>>> 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'
askewchan
  • 45,161
  • 17
  • 118
  • 134
41

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'

Sort letters and make them distinct while keeping caps:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'

Sort letters and keep duplicates:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'

If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'
Radek
  • 1,530
  • 16
  • 20
  • Hey, that first solution was kinda useful for a piece of homework in which I had to find a letter using bisection. Yes, I already know about the string class and the find() method, but this defeats the purpose of the exercise ;) – runlevel0 Jan 18 '18 at 15:52
13

Python functionsorted returns ASCII based result for string.

INCORRECT: In the example below, e and d is behind H and W due it's to ASCII value.

>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'

CORRECT: In order to write the sorted string without changing the case of letter. Use the code:

>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'

OR (Ref: https://docs.python.org/3/library/functions.html#sorted)

>>> a = "Hello World!"
>>> "".join(sorted(a,key=str.lower))
' !deHllloorW'

If you want to remove all punctuation and numbers. Use the code:

>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'
ajnoha
  • 36
  • 5
Priyank Arora
  • 477
  • 4
  • 7
10

You can use reduce

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'
Saquib
  • 273
  • 3
  • 9
3

the code can be used to sort string in alphabetical order without using any inbuilt function of python

k = input("Enter any string again ")

li = []
x = len(k)
for i in range (0,x):
    li.append(k[i])

print("List is : ",li)


for i in range(0,x):
    for j in range(0,x):
        if li[i]<li[j]:
            temp = li[i]
            li[i]=li[j]
            li[j]=temp
j=""

for i in range(0,x):
    j = j+li[i]

print("After sorting String is : ",j)
Kanan Joshi
  • 141
  • 1
  • 4
1

Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().

from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])

sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']

tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')

We are selecting the last index (-1) of the tuple

Mono
  • 146
  • 4
  • Well done for your first answer. Just consider a string of 1 million characters, your tuple() command will create a huge list of accumulated options which uses unnecessarily large amount of memory. – tda Sep 04 '18 at 10:28
  • Agreed. So, to improve space complexity, the idea is to work with the iterable itself, instaed of converting it to a data structure. Nice. Thank You. – Mono Sep 04 '18 at 12:15