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

后端 未结 13 943
梦谈多话
梦谈多话 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:33

    MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter that will work:

    from collections import Counter
    import string
    
    def count_letters(word, valid_letters=string.ascii_letters):
        count = Counter(word) # this counts all the letters, including invalid ones
        return sum(count[letter] for letter in valid_letters) # add up valid letters
    

    Example output:

    >>> count_letters("The grey old fox is an idiot.") # the period will be ignored
    22
    

提交回复
热议问题