Skip to content
Advertisement

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

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)

Advertisement

Answer

You can pass a custom key function to sort with.

words.sort(key=lambda s: (s[0].isupper(), s))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement