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

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

    OK, if that's what you want, here's what I would do to fix your existing code:

    from collections import Counter
    
    def count_letters(words):
        counter = Counter()
        for word in words.split():
            counter.update(word)
        return sum(counter.itervalues())
    
    words = "The grey old fox is an idiot"
    print count_letters(words)  # 22
    

    If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for loop if not sooner.

提交回复
热议问题