Question: Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?' Expected Output : No. of Upper case characters : 4 No. of Lower case Characters : 33
function:
def up_low(s):
for a in s:
u = u.count(a.isupper())
l = l.count(a.islowwer())
print(u, l)
why this one doesn't work?
You can use List comprehensions and sum function to get the total number of upper and lower case letters.
def up_low(s):
u = sum(1 for i in s if i.isupper())
l = sum(1 for i in s if i.islower())
print( "No. of Upper case characters : %s,No. of Lower case characters : %s" % (u,l))
up_low("Hello Mr. Rogers, how are you this fine Tuesday?")
Output: No. of Upper case characters : 4,No. of Lower case characters : 33
You are understanding wrong the count function, count, first of all, is a string functrion, and as parameter take a string, instead of doing this, you can simply do:
def up_low(string):
uppers = 0
lowers = 0
for char in string:
if char.islower():
lowers += 1
elif char.isupper():
uppers +=1
else: #I added an extra case for the rest of the chars that aren't lower non upper
pass
return(uppers, lowers)
print(up_low('Hello Mr. Rogers, how are you this fine Tuesday?'))
4 33
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