How do I use regular expressions to count the number of digits in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I use regular expressions to count the number of digits in python?

11th Jan 2019, 9:04 AM
Opegbemi Ayo
4 Answers
+ 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')))
11th Jan 2019, 1:59 PM
Anna
Anna - avatar
+ 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).
11th Jan 2019, 9:10 AM
HonFu
HonFu - avatar
+ 3
You can transform a string into a list of words and just count them. len(your_string.split())
11th Jan 2019, 1:11 PM
HonFu
HonFu - avatar
+ 1
What of the regular expression for counting the number of words in a string?
11th Jan 2019, 1:09 PM
Opegbemi Ayo