count the number of upper case and lower case characters in word

21,497

Solution 1

You may use map with str.isupper and str.islower to find the count of uppercased and lowercased characters respectively as:

>>> my_word = "HelLo WorLd"
>>> lower_count = sum(map(str.islower, my_word))
>>> lower_count
6

>>> upper_count = sum(map(str.isupper, my_word))
>>> upper_count
4

Solution 2

Count in one line using collections.Counter, generator comprehension and a nested ternary:

import collections

my_word = "HelLo WorLd"
c = collections.Counter("upper" if x.isupper() else "lower" if x.islower() else "" for x in my_word)
print(c)

result:

Counter({'lower': 6, 'upper': 4, '': 1})
Share:
21,497
Admin
Author by

Admin

Updated on April 15, 2020

Comments

  • Admin
    Admin about 4 years
    def Charater(): 
        UpperCount = 0 
        LowerCount = 0
        word = input('Enter a word: ')
        for letter in word:
            if letter == letter.upper 
                UpperCount = UpperCount + 1
                return UpperCount
            else:
                LowerCount = LowerCount + 1
                return LowerCount
    
    print(Charater())
    

    Please don't judge me if this looks bad. But am a beginner I am trying to make the code count how many upper and lower case characters in a word which is inputted by the user. Each time I do this it returns 1. (Its probably my if statement). can someone please point out the problem and tell me how to resolve it.

  • juanpa.arrivillaga
    juanpa.arrivillaga about 7 years
    you should just use 'some_string'.isupper()
  • Elmex80s
    Elmex80s about 7 years
    @juanpa.arrivillaga Thanks fixed it
  • juanpa.arrivillaga
    juanpa.arrivillaga about 7 years
    Personally, I prefer to use sum if I just want to count when sum boolean condition is True, so sum(map(str.islower, word)) for example. It also has the advantage of being python 2-3 compatible.
  • Moinuddin Quadri
    Moinuddin Quadri about 7 years
    @juanpa.arrivillaga makes sense. Also as I see that OP is looking for Python3 solution, updated the answer