codingwarrior
codingwarrior

Reputation: 49

How to print only uppercase letters in Python using isupper( ) method?

I am trying to write a function that uses a for loop and the isupper method to print only the uppercase letters of a string.

what i have done so far:

upper_chars = ""
def only_upper(s):
    for char in s:
        if s.isupper() == True:
        upper_chars += char
 print upper_chars

But this is not working? Anyone tell me why? I get this error message: "UnboundLocalError: local variable 'upper_chars' referenced before assignment"

Upvotes: 4

Views: 28728

Answers (2)

nathanhorton
nathanhorton

Reputation: 100

Well a way to fix part of the problem is to make sure you call the actually function, another thing is to make sure you return the modified string, Also you if statement is not written correctly, the body of the function needs to be 4 spaces across from the beginning of the function.

Example using the isupper method and for loop

def upperOnly(s):
    onlyCaps = ""
    for char in s:
        if char.isupper() == True:
            onlyCaps += char
    return onlyCaps 
print upperOnly("TeSt")

Upvotes: 0

alecxe
alecxe

Reputation: 473873

Several problems in your code:

  • you should define upper_chars variable inside the function
  • in the loop you should call isupper() on a character, not the whole string
  • your function should return something
  • you should call the function
  • wrong indentation in the if block

Here's the code with fixes:

def only_upper(s):
    upper_chars = ""
    for char in s:
        if char.isupper():
            upper_chars += char
    return upper_chars

print only_upper("HeLLo WorLD")

Also, you can use filter():

def only_upper(s):
    return filter(lambda x: x.isupper(), s)

print only_upper("HeLLo WorLD")

Or:

def only_upper(s):
    return "".join(c for c in s if c.isupper())

print only_upper("HeLLo WorLD")

Both print:

HLLWLD

Upvotes: 10

Related Questions