0

I am new to python and i'm trying to learn it. I was recently trying out sorting, like basic sorting of strings. In my code i am passing in a string to a function print_sorted(), this string is then passed along to the sort_sentence function which breaks the sentence into words and then sorts it using python's sorted() function. But for some reason it always ignores the first string before sorting. Can someone please tell me why? Cheers in advance !!

def break_words(stuff):
    words = stuff.split( )
    return words

def sort_words(words):
    t = sorted(words)
    return t

def sort_sentence(sentence):
    words = break_words(sentence)
    return sort_words(words)

def print_sorted(sentence):
    words = sort_sentence(sentence)
    print words

print_sorted("Why on earth is the sorting not working properly")

Returns this ---> ['Why', 'earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'working']
Tim Peters
  • 67,464
  • 13
  • 126
  • 132
Johny
  • 1

1 Answers1

3

Your output seems correct because uppercase letters come before lowercase letters.

If you want to ignore case while sorting you can call str.lower for the key parameter in sorted(), something like this:

>>> sorted("Why on earth is the sorting not working properly".split())
['Why', 'earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'working']
>>> sorted("Why on earth is the sorting not working properly".split(), key=str.lower)
['earth', 'is', 'not', 'on', 'properly', 'sorting', 'the', 'Why', 'working']
riteshtch
  • 8,629
  • 4
  • 25
  • 38