Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count lower case characters in a string

Tags:

python

What is the most pythonic and/or efficient way to count the number of characters in a string that are lowercase?

Here's the first thing that came to mind:

def n_lower_chars(string):
    return sum([int(c.islower()) for c in string])
like image 726
mhowison Avatar asked Jun 08 '12 17:06

mhowison


2 Answers

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.

like image 101
brandizzi Avatar answered Sep 20 '22 16:09

brandizzi


def n_lower_chars(string):
    return len(filter(str.islower, string))
like image 43
Swiss Avatar answered Sep 21 '22 16:09

Swiss