prince banana
prince banana

Reputation: 1

Using 'sorted' function for words gives an output with letters being split and sorted

I'm new to python (2.7) and stackoverflow. I'm trying to learn how to use the 'sorted' function. When I use the 'sorted' function, the sentence splits into individual letters and sorts those letters in ascending order. But that is not what I want. I want to sort my words in ascending order. I'm trying to run this code

peace = "This is one of the most useful sentences in the whole wide world."

def pinkan (one):
    return sorted (one)

print pinkan (peace)

But the output I get is something of this sort:

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'c', 'd', 
'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f'
, 'h', 'h', 'h', 'h', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'm', 'n', 'n', 'n', 
'n', 'o', 'o', 'o', 'o', 'o', 'r', 's', 's', 's', 's', 's
', 's', 't', 't', 't', 't', 'u', 'u', 'w', 'w', 'w']

I would appreciate any help/suggestion. Thanks :-)

Upvotes: 0

Views: 193

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521379

You should be using first split() to generate a list of words, then sort(), to sort that list alphabetically in ascending order:

peace = "This is one of the most useful sentences in the whole wide world."
terms = peace.split()
terms.sort(key=str.lower)
output = " ".join(terms)
print(output)

['in', 'is', 'most', 'of', 'one', 'sentences', 'the', 'the', 'This', 'useful',
    'whole', 'wide', 'world.']

Upvotes: 1

Related Questions