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

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


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


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

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

Alphabetical:

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

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


You shouldn't be setting x = []. That is setting an empty list to your inputted parameter. Furthermore, use python's for i in x syntax as follows:

for i in x:    if i.isalpha():        letters+=1    elif i.isnumeric():        digit+=1    elif i.isspace():        space+=1    else:        other+=1