If I have a string "cab", I want to sort the string alphabetically to get "abc". The sorted() function returns a list instead of a string. For example, I tried the following:
str = "cab" sorted_str = sorted(str) print(sorted_str)
and it prints ['a', 'b', 'c'] instead of 'abc'. I can use a for loop to create another string like this and it prints 'abc', but it's cumbersome:
new_sorted_str = ''
for i in range(len(sorted_str)):
new_sorted_str += sorted_str[i]
print(new_sorted_str) Is there a better way?
.
Videos
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
>>> 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'
I have a string that looks like this:
myStr = 'ABC-5, XYZ-2, ABC-21, JKL-34, ABC-1, ETC...'
I want to sort it so it looks like:
myStr = 'ABC-1, ABC-5, ETC..'
How do I go about this? Everytime I try it just outputs a very messy string.