Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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):     length = len(x)     digit = 0     letters = 0     space = 0     other = 0     for i in x:         if x[i].isalpha():             letters += 1         elif x[i].isnumeric():             digit += 1         elif x[i].isspace():             space += 1         else:             other += 1     return number,word,space,other 

But it's not working:

>>> count(asdfkasdflasdfl222) Traceback (most recent call last):   File "<pyshell#4>", line 1, in <module>     count(asdfkasdflasdfl222) NameError: name 'asdfkasdflasdfl222' is not defined 

What's wrong with my code and how can I improve it to a more simple and precise solution?

like image 427
ray Avatar asked Jul 22 '14 02:07

ray


People also ask

How do you count digits and letters in Python?

First we find all the digits in string with the help of re. findall() which give list of matched pattern with the help of len we calculate the length of list and similarly we find the total letters in string with the help of re. findall() method and calculate the length of list using len.


2 Answers

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 
like image 164
Óscar López Avatar answered Sep 20 '22 22:09

Óscar López


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

like image 44
brickbobed Avatar answered Sep 18 '22 22:09

brickbobed