How to count the number of letters in a string without the spaces?

后端 未结 13 933
梦谈多话
梦谈多话 2020-12-31 07:45

This is my solution resulting in an error. Returns 0

PS: I\'d still love a fix to my code :)

from collections import Counter
import          


        
13条回答
  •  长发绾君心
    2020-12-31 08:18

    Simply solution using the sum function:

    sum(c != ' ' for c in word)
    

    It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.

    It's worth to mention that c != ' ' returns True or False, which is a value of type bool, but bool is a subtype of int, so you can sum up bool values (True corresponds to 1 and False corresponds to 0)

    You can check for an inheretance using the mro method:

    >>> bool.mro() # Method Resolution Order
    [, , ]
    

    Here you see that bool is a subtype of int which is a subtype of object.

提交回复
热议问题