Read lowercase characters in a string

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

Here is the first thing that came to mind:

def n_lower_chars(string): return sum([int(c.islower()) for c in string]) 
+7
source share
4 answers

Your tricky trick! However, I find it more convenient to read the lower characters, adding 1 for each.

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

In addition, we do not need to create a new list for this, so removing [] will cause sum() to work on an iterator that consumes less memory.

+12
source
 def n_lower_chars(string): return len(filter(str.islower, string)) 
+7
source
 def n_lower_chars(string): return sum(map(str.islower, string)) 
+5
source

If you want to separate things a little more subtly:

 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) 
+2
source

Source: https://habr.com/ru/post/917651/


All Articles