How to count digits, letters, spaces for a string in Python?
138,082
Solution 1
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
Solution 2
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
Solution 3
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
Solution 4
# Write a Python program that accepts a string and calculate the number of digits
# andletters.
stre =input("enter the string-->")
countl = 0
countn = 0
counto = 0
for i in stre:
if i.isalpha():
countl += 1
elif i.isdigit():
countn += 1
else:
counto += 1
print("The number of letters are --", countl)
print("The number of numbers are --", countn)
print("The number of characters are --", counto)
Author by
ray
Updated on July 09, 2022Comments
-
ray almost 2 years
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?
-
Óscar López almost 10 years@sundarnatarajСундар it's a trade-off. Sure, it iterates 3 times over the input string, but I believe it's easier to read like this.
-
Raymond Hettinger almost 10 years+1 The solution is cleaner when you separate the tasks. Nice work! To make it fast, consider using itertools.imap() like this:
numbers = sum(imap(str.isdigit, s))
. After the initial calls, that will run at C-speed with no pure python steps and no method lookups. -
ray almost 10 yearsthe indentation is right( got wrong when copy to stackoverflow). the reason I used x=[] is try to let Python know that x is a list. if I delete x=[], it showed : >>> count(aasdfs1111xxx) Traceback (most recent call last): File "<pyshell#250>", line 1, in <module> count(aasdfs1111xxx) NameError: name 'aasdfs1111xxx' is not defined
-
ray almost 10 yearsHI, If I removed x = [], the it got error when I run. it said the strings I typed is " not defined".
-
Abhishek Mittal almost 10 yearsI execute this code by comment out x = [] and it is working fine. One more error in your code is that you need to use isdigit instead of isnumberic. Here, I am assuming that count function is called by passing string in x argument. Like : count ("1233AASD 43") Please let me know if it does not solve your problem.
-
Massimiliano Kraus almost 7 yearsWelcome to StackOverflow. You better explain your solution, instead of just posting anonymous code. Maybe you should read How do I write a good answer, especially when it says Brevity is acceptable, but fuller explanations are better.
-
Óscar López over 6 years@ShubhamS.Naik True is taken as 1 for the purpose of a sum
-
Shubham S. Naik over 6 yearsThanks @ÓscarLópez I agree that True is taken as 1, however I want to know numbers = sum(c.isdigit() for c in s) is generating which iterable?? As sum(1) returns as below: >>> sum(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
-
Óscar López over 6 yearsThe inside of sum is a generator expression, I simply removed the surrounding () because they’re redundant
-
Shubham S. Naik over 6 years@ÓscarLópez which data structure (iterable) does it generate ?
-
Óscar López over 6 yearsAs I said: a generator expression. Read about it in the docs.
-
Shubham S. Naik over 6 years@ÓscarLópez I will read about 'generator expression' . Thanks a lot !!
-
Tim over 5 yearsThis doesn't actually answer the question. The question was to count the number of digits, letters and spaces, not to find all instances of numbers.