In this post, I am going to explain how to count the number of digits in a string with Python. I will explain how I extract the digits out Strings. This is common in the Data Science Domain.
I can count the number of digits with a simple for loop. I loop through all characters in a string and check if it is a digit. In my previous post Three words in python, I explained the isdigit function already. I make use of this function in this problem too. I increment a counter when the character is a digit. A very simple for loop.
text = "I am 1 string with 2 digits" count = 0 for char in text: if char.isdigit(): count += 1 print("the number of digits is: " + str(count))
Python has list comprehensions. With the build in function sum I can do the same. The sum function requires an iterable as input parameter.
text = "I am 1 string with 2 digits" count = sum(1 for x in text if x.isdigit()) print("the number of digits is: " + str(count))
The sum function can operate on an array of Booleans too. A True value will act like a 1 and a False will act like a 0. Consider the following example.
result = sum([True,True,False]) print(result) # This will print 2
This results in the following result:
text = "I am 1 string with 2 digits" count = sum(x.isdigit() for x in text) print("the number of digits is: " + str(count))
With regular expressions
I can also use the re package. The following example first removes all non digit characters. The remaining is a string with only characters. This means that I only have to take the length of the string to know how many digits are present in the string.
import re text = "I am 1 string with 2 digits"
count = re.sub("\D", "", test_string)print("the number of digits is: " + len(count))
As last one I also can make use of the built in String method count. Just count all digits in the string and add the numbers together with the sum method.
return sum(text.count(digit) for digit in '1234567890')
There are several ways to count the number of digits in a string with Python. I showed some of them here. I hope these tips can help you with similar problems while coding.