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']
2
  • 2
    Are you asking why 'Why' comes before 'earth'? It's unclear. But if that's it, uppercase letters precede lowercase letters; e.g., "W" < "e" returns True. Commented Oct 24, 2016 at 1:09
  • 1
    It is working. What output were you expecting? Commented Oct 24, 2016 at 1:09

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers guys. ametuar mistake, just didn't think of that part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.