Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 804
codingwarrior Avatar asked Oct 14 '25 08:10

codingwarrior


1 Answers

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
like image 125
alecxe Avatar answered Oct 16 '25 21:10

alecxe