Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters

Tags:

python

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?

like image 893
a81884855 Avatar asked Jan 22 '26 12:01

a81884855


2 Answers

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

like image 115
Bharath Avatar answered Jan 24 '26 02:01

Bharath


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

like image 31
A Monad is a Monoid Avatar answered Jan 24 '26 01:01

A Monad is a Monoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!