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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With