0

I'm trying to create a function that checks the number of upper and lower case letters in a phrase.

This is the code that I'm using:

def letter_counter(a):
  '''A function to sort the letters in a string'''
  print('The phrase "' + a + '" has: \n')

  upper_case = []
  lower_case = []

  string_to_list = list(a)

  for ltr in string_to_list:
    if ltr == ltr.lower():
      string_to_list.remove(ltr)
      lower_case.append(ltr)
    elif ltr == ltr.upper():
      string_to_list.remove(ltr)
      upper_case.append(ltr)
    else:
      pass

  print('Lower Case Letters: ' + str(len(lower_case)))
  print('Upper Case Letters: ' + str(len(upper_case)))


letter_counter('My name is Earl.')

And this is the result:

The phrase "My name is Earl." has:
Lower Case Letters: 7
Upper Case Letters: 1

What am I doing incorrectly?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You could use sum, a generator expression, also use str.islower and str.isupper:

print("Lower Case Letters", sum(1 for ch in phrase if ch.islower()))
print("Upper Case Letters", sum(1 for ch in phrase if ch.isupper()))

Anyway if you want your code to work, you should change your loop. First of all you should avoid doing removes in the list you are going through at the same time. Also you should check if ltr is really a letter and not for example a space or point.

for ltr in string_to_list:
    if ltr == ltr.lower() and ltr.isalpha():
        lower_case.append(ltr)
    elif ltr == ltr.upper() and ltr.isalpha():
       upper_case.append(ltr)