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"
Several problems in your code:
upper_chars
variable inside the functionisupper()
on a character, not the whole stringif
blockHere'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With