Home > Enterprise >  Python: How do you make a list start with the lowercase strings?
Python: How do you make a list start with the lowercase strings?

Time:12-08

I'm currently making a simple code that allows the user to input a sentence or a group of words and the program will sort the words alphabetically. This initial code works great but unfortunately, it prints out the uppercase words first and then the lowercase words. I was hoping if there was a simple way to reverse this and have the lowercase words go first on the list instead of the uppercase words. Any help would be greatly appreciated!

strings = input("Enter words: ")

words = strings.split()

words.sort()

print("The sorted words are:")
for word in words:
    print(word)

CodePudding user response:

You can pass a custom key function to sort with.

words.sort(key=lambda s: (s[0].isupper(), s))

CodePudding user response:

You could do words.sort(key=str.isupper) after your first sort.

CodePudding user response:

By default, Python sorts strings according to the ordinal value of each character (ord(c)), which corresponds to its ASCII value for English alphabet. In ASCII, the uppercase letters have lower value than lowercase letters, which is why you have this kind of result.

To modify this behavior, you need to modify the key in your sort function. For example, if you wanted a case insensitive sorting, you could do the following:

words.sort(key=str.lower)

In your case, you need to implement two rules:

  1. Case-insensitive sorting (e.g. 'alice' < 'bob' < 'dylan'): can be done with str.lower
  2. Among words with same characters, but different case, put the uppercase version last (e.g. 'alice' < 'Alice' < 'ALICE'): can be done by reverting the original ASCII ordering with str.swapcase

You can implement these two rules at once with a key function that returns a tuple (rule1, rule2). More information about that here.

words.sort(key=lambda x: (x.lower, x.swapcase))
  • Related