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?
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