Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the letters of a one worded string in Python?

x = 'yellow'
print(sorted(x))

returns

['e', 'l', 'l', 'o', 'w', 'y']

What I want it to return

ellowy

How ran I make it return 'ellowy' without the letters being in a list?

like image 984
Brennan Hoeting Avatar asked Jul 12 '12 18:07

Brennan Hoeting


3 Answers

Actually sorted() when used on a string always returns a list of individual characters. so you should use str.join() to make a string out of that list.

>>> x = 'yellow'
>>> ''.join(sorted(x))
'ellowy'
like image 116
Ashwini Chaudhary Avatar answered Nov 15 '22 14:11

Ashwini Chaudhary


The join() method of a string joins each element of its argument with copies of the given string object as a delimiter between each item. Many people find this a weird and counterintuitive way to do things, but by joining the elements with an empty string you can convert a list of strings into a single string:

x = 'yellow' 
print(''.join(sorted(x)))
like image 38
Russell Borogove Avatar answered Nov 15 '22 15:11

Russell Borogove


x = 'yellow' 
print(''.join(sorted(x)))
like image 32
Maria Zverina Avatar answered Nov 15 '22 15:11

Maria Zverina