Count lower case characters in a string

Clever trick of yours! However, I find it more readable to filter the lower chars, adding 1 for each one.

def n_lower_chars(string):
    return sum(1 for c in string if c.islower())

Also, we do not need to create a new list for that, so removing the [] will make sum() work over an iterator, which consumes less memory.


If you want to divide things a little more finely:

from collections import Counter

text = "ABC abc 123"
print Counter("lower" if c.islower() else 
              "upper" if c.isupper() else
              "neither" for c in text)

def n_lower_chars(string):
    return len(filter(str.islower, string))

def n_lower_chars(string):
    return sum(map(str.islower, string))

Tags:

Python