Arsenii
Arsenii

Reputation: 109

How do I organize lower and upper case words in Python?

Here is the code I have.

All I need to do is make sure the list is organized with upper case words first and lower case words second. I looked around but no luck with .sort or .sorted command.

string = input("Please type in a string? ")

words = string.strip().split()
for word in words:
    print(word)

Upvotes: 0

Views: 3049

Answers (2)

Justin
Justin

Reputation: 66

string = raw_input("Please type in a string? ")
words = string.strip().split()
words.sort()

As to how to separate upper and lower case words into separate columns:

string = raw_input("Please type in a string? ")
words = string.split()
column1 = []
column2 = []
for word in words:
    if word.islower():
        column1.append(word)
    else
        column2.append(word)

The .islower() function evaluates to true if all the letters are lower case. If this doesn't work for your problem's definition of upper and lower case, look into the .isupper() and .istitle() methods here.

Upvotes: 1

Jollywatt
Jollywatt

Reputation: 1365

The sorted() function should sort items alphabetically taking caps into account.

>>> string = "Don't touch that, Zaphod Beeblebox!"
>>> words = string.split()
>>> print( sorted(words) )
['Beeblebox!', "Don't", 'Zaphod', 'that,', 'touch']

But if for some reason sorted() ignored caps, then you could do it manually with a sort of list comprehension if you wanted:

words = sorted([i for i in words if i[0].isupper()]) + sorted([i for i in words if i[0].islower()])

This creates two separate lists, the first with capitalized words and the second without, then sorts both individually and conjoins them to give the same result.

But in the end you should definitely just use sorted(); it's much more efficient and concise.


EDIT: Sorry, I might have miss-interpreted your question; if you want to organize just Caps and not without sorting alphabetically, then this works:

>>> string = "ONE TWO one THREE two three FOUR"
>>> words = string.split()
>>> l = []
>>> print [i for i in [i if i[0].isupper() else l.append(i) for i in words] if i!=None]+l
['ONE', 'TWO', 'THREE', 'FOUR', 'one', 'two', 'three']

I can't find a method that's more efficient then that, so there you go.

Upvotes: 1

Related Questions