Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to detect all words that start with a capital letter in a string

Tags:

python

I'm writing out a small snippet that grabs all letters that start with a capital letter in python . Here's my code

def WordSplitter(n):
    list1=[]
    words=n.split()
    print words

    #print all([word[0].isupper() for word in words])
    if ([word[0].isupper() for word in words]):
        list1.append(word)
    print list1

WordSplitter("Hello How Are You")

Now when I run the above code. Im expecting that list will contain all the elements, from the string , since all of the words in it start with a capital letter. But here's my output:

@ubuntu:~/py-scripts$ python wordsplit.py 
['Hello', 'How', 'Are', 'You']
['You']# Im expecting this list to contain all words that start with a capital letter
like image 721
seeker Avatar asked Nov 03 '12 02:11

seeker


2 Answers

You're only evaluating it once, so you get a list of True and it only appends the last item.

print [word for word in words if word[0].isupper() ]

or

for word in words:
    if word[0].isupper():
        list1.append(word)
like image 66
Joran Beasley Avatar answered Sep 27 '22 02:09

Joran Beasley


You can take advantage of the filter function:

l = ['How', 'are', 'You']
print filter(str.istitle, l)
like image 30
Yevgen Yampolskiy Avatar answered Sep 27 '22 02:09

Yevgen Yampolskiy