How to sort the letters in a string alphabetically in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:24 Accepted answer (Score 358)
00:36 Answer 2 (Score 110)
00:59 Answer 3 (Score 38)
01:47 Answer 4 (Score 13)
02:35 Thank you
--
Full question
https://stackoverflow.com/questions/1504...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:24 Accepted answer (Score 358)
00:36 Answer 2 (Score 110)
00:59 Answer 3 (Score 38)
01:47 Answer 4 (Score 13)
02:35 Thank you
--
Full question
https://stackoverflow.com/questions/1504...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
ACCEPTED ANSWER
Score 396
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
ANSWER 2
Score 118
>>> 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'
ANSWER 3
Score 42
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'
ANSWER 4
Score 10
You can use functools.reduce
>>> from functools import reduce
>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'