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?
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.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With