How to count digits, letters, spaces for a string in Python?

前端 未结 9 1313
忘了有多久
忘了有多久 2020-12-01 08:14

I am trying to make a function to detect how many digits, letter, spaces, and others for a string.

Here\'s what I have so far:

def count(x):
    leng         


        
相关标签:
9条回答
  • 2020-12-01 08:41

    Here's another option:

    s = 'some string'
    
    numbers = sum(c.isdigit() for c in s)
    letters = sum(c.isalpha() for c in s)
    spaces  = sum(c.isspace() for c in s)
    others  = len(s) - numbers - letters - spaces
    
    0 讨论(0)
  • 2020-12-01 08:42

    Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.

    import re
    len(re.sub("[^0-9]", "", my_string))
    

    Alphabetical:

    import re
    len(re.sub("[^a-zA-Z]", "", my_string))
    

    More info - https://docs.python.org/3/library/re.html

    0 讨论(0)
  • 2020-12-01 08:46
    def match_string(words):
        nums = 0
        letter = 0
        other = 0
        for i in words :
            if i.isalpha():
                letter+=1
            elif i.isdigit():
                nums+=1
            else:
                other+=1
        return nums,letter,other
    
    x = match_string("Hello World")
    print(x)
    >>>
    (0, 10, 2)
    >>>
    
    0 讨论(0)
提交回复
热议问题