Getting just the upper case letters from a string

1.5k views Asked by At

I have just started to learn python and I'm just making programs to practice the new topic I have learnt, so please be gentle :)

I try to have a var = to a sentence then check for upper case letters then append the upper case letters to a list. If I change l = o[6] I get 'G' so the append and .isupper() is working but I can't seem to get the i to work, I thought it might be i is becoming a string but i is declared as a an int (python 3.6).

This is what i have so far:

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
i = 0
l = o[i]

if l.isupper() == True:
   upperCase.append(l)

else:
    i += 1

print (upperCase)
4

There are 4 answers

5
martianwars On

You need to use a loop to build up this list. A for loop is very simple to build in Python. It simply iterates over all the letters one by one. Try to modify the code to,

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
for i in range(0, len(o)):
    l = o[i]  
    if l.isupper() == True:
       upperCase.append(l)

print (upperCase)

Of course, there are better ways to do it. You don't need to explicitely define l = o[i]. You can do that as part of the loop! Also, you don't need the == True. Something like this -

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
for l in o:
    if l.isupper():
       upperCase.append(l)

print (upperCase)

Even better, use filter and lambda.

print(filter(lambda l: l.isupper(), o))
0
Artagel On

You can do this much simpler.

o = "the doG jUmPeD ovEr The MOOn"
upperCase = []
for letter in o:
    if letter.isupper():
        upperCase.append(letter)

print(upperCase)

Simply iterate over the string, it'll do so one letter at a time.

1
NinjaGaiden On

You can also try the list comphresion

upperCase= [ i for i in o if i.isupper() ]
1
Moinuddin Quadri On

As an alternative, you may use filter with str.upper as:

>>> o = "the doG jUmPeD ovEr The MOOn"

# Python 2
>>> filter(str.isupper, o)
'GUPDETMOO'

# Python 3
>>> ''.join(filter(str.isupper, o))
'GUPDETMOO'