I want to count the number of numbers in s string.
In this string:
"2019 was a great year for 10 fortunate people in ages 20 to 60."
The result should be 4 (2019, 10, 20, 60) Thanks
For counting integers only, you can use a simple regular expression:
import re
s = '2019 was a great year for 10 fortunate people in ages 20 to 60.'
n = len(re.findall(r'\d+', s)) # 4
Here '\d+'
means "one or more decimal characters in a row".
Note that re.findall
produces a list
of the results. If you only care about the number of elements (n
), this is wasteful for input strings containing very many numbers. Instead, make use of an iterator approach, e.g.
import re
s = '2019 was a great year for 10 fortunate people in ages 20 to 60.'
n = sum(1 for _ in re.finditer(r'\d+', s)) # 4
Let's say that you allow float
s like 1.2
and 3e-4
etc. as well. The corresponding regular expression is now much more complicated, and an easier solution would be to just loop over all "words" in the string and check if they can be interpreted as a number:
def is_number(num):
try:
float(num)
except:
return False
return True
s = '2019 was a great year for 10 fortunate people in ages 20 to 60.'
n = sum(1 for num in s.split() if is_number(num)) # 4