-2

I wrote a function which takes a string and gives back the count of small letters and the count of capital letters in that string. The program works for single word but as soon I add two words containing 'space' in between two words, messes things up. spaces counts too. What is your thoughts?

def myfunc(s):
    s = str(s)

    upperl = 0
    lowerl = 0
    for i in s:
        if i == i.lower():
            lowerl += 1
        if i == i.upper():
            upperl += 1
        if i == ' ':
            continue
    return upperl,lowerl

x = myfunc('hello G')
print (x)

from the word 'hello G' we expect upper letter and lower letter count as 1,5 but that space between two words makes it 2,6.

iDrwish
  • 3,085
  • 1
  • 15
  • 24
  • Possible duplicate: https://stackoverflow.com/questions/18129830/count-the-uppercase-letters-in-a-string-with-python (NB this solution solves space issue) – Grzegorz Skibinski Sep 01 '19 at 09:21

3 Answers3

0

The problem is that ' ' == ' '.upper() and ' ' == ' '.lower() are both true, and you're not checking whether you're currently dealing with an alphanumeric character or something else. Instead, you can check whether you're working with a lowercase letter or an uppercase letter.

Try this:

def calculate_case_count(string: str):
    string = str(string)
    upper_letter_count = 0
    lower_letter_count = 0
    for letter in string:
        if letter.islower():
            lower_letter_count += 1
        elif letter.isupper():
            upper_letter_count += 1
    return upper_letter_count, lower_letter_count


result = calculate_case_count('hello    G ')
print(result) # (1, 5)
pneuma
  • 917
  • 5
  • 10
0

Using regex will be cleaner solution here

import re

def count_letter_cases(text):
    n_lower = len(re.findall("[a-z]", text))
    n_upper = len(re.findall("[A-Z]", text))
    return n_lower, n_upper

print(count_letter_cases("Hello Goat"))
## Result: (7,2)
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33
  • I'd say there's no need to use regex here, having methods from the builtin `str` class to do this. And by no means it is cleaner than simply mapping these `str` methods to the strings and taking the `sum` (simplest solution I can think of) – yatu Sep 01 '19 at 09:33
  • ya, It looks for this case it is not necessary, but it has one benefit, you can similarly extend it to count number or other special characters – Dev Khadka Sep 01 '19 at 09:38
-1
from collections import Counter

def count_cases(strng):
    counts = Counter(strng)
    upper = 0
    lower = 0
    for char, count in counts.items():
        if char.isupper():
            upper += count
        elif char.islower():
            lower += count
    return (upper, lower)

Edit: Removed string module. Using internal islower and isupper methods.

awakenedhaki
  • 186
  • 5