0
How do I use regular expressions to count the number of digits in python?
4 Respuestas
+ 2
If you need to do it with regex:
import re
#number of words in a string
print(len(re.compile(r'\w+?\b').findall('your string goes here')))
# number of digits in a string
print(len(re.compile(r'\d').findall('your string goes here')))
+ 6
Better question: Why?
You can easily do it without re, for example:
sum(s.isdigit() for s in your_str)
When you're confident the string only contains digits, you can just use len(your_str).
+ 3
You can transform a string into a list of words and just count them.
len(your_string.split())
+ 1
What of the regular expression for counting the number of words in a string?