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

后端 未结 13 841
梦谈多话
梦谈多话 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:28
    string=str(input("Enter any sentence: "))
    s=string.split()
    a=0
    b=0
    
    for i in s:
        a=len(i)
        b=a+b
    
    print(b)
    

    It works perfectly without counting spaces of a string

    0 讨论(0)
  • 2020-12-31 08:31

    I managed to condense it into two lines of code:

    string = input("Enter your string\n")
    print(len(string) - string.count(" "))
    
    0 讨论(0)
  • 2020-12-31 08:32

    Counting number of letters in a string using regex.

    import re
    s = 'The grey old fox is an idiot'
    count = len(re.findall('[a-zA-Z]',s))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-31 08:35
    def count_letter(string):
        count = 0
        for i in range(len(string)):
            if string[i].isalpha():
                count += 1
        return count
    
    
    print(count_letter('The grey old fox is an idiot.'))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题