Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to sort the letters in a string alphabetically keeping distinction between uppercases and lowercases

I am trying to order the words of a string in a particular way: In my code below the output is "MNWdeorwy" but i would like it to be "deMNorWwy" (so i need to keep the letters ordered despite being upper o lowercases) Could you please help me to understand where I am wrong and why? Thank you

wrd = "MyNewWord"

def order_word(s):
    if s == "":
        return "Invalid String!"
    else:
        c = sorted(s)
        d = ''.join(sorted(c))
        return d

print order_word(wrd)

I would like to precise that my question is different from the following: How to sort the letters in a string alphabetically in Python : in fact, the answers given in the link does not consider the difference between upper and lowercases in a string.

like image 794
Marco Giuseppe de Pinto Avatar asked Dec 15 '22 07:12

Marco Giuseppe de Pinto


1 Answers

sorted() sorts based off of the ordinal of each character. Capital letters have ordinals that are lower than all lowercase letters. If you want different behavior, you'll need to define your own key:

c = sorted(s, key=lambda c: (c.lower(), c.islower()))

That way, c would be sorted by ('c', 1) and C is sorted by ('c', 0). Both come before ('d', ...) or ('e', ...) etc., but the capital C is earlier (lower) than the lowercase c.

By the way, you shouldn't say d = "".join(sorted(c)) because c has already been sorted. Just do d = "".join(c)

like image 145
zondo Avatar answered Dec 16 '22 19:12

zondo