Python Program to Count the Number of Digits in a String

1. Introduction

Counting the number of digits within a string is a frequent operation in data processing, which can be utilized to validate input or parse numerical data. Python's strong type handling makes it simple to perform such checks.

Digits are numerical characters from 0 to 9. In a string that may contain a mix of different types of characters, we are often interested in counting how many of these characters are digits.

2. Program Steps

1. Initialize the string to be examined.

2. Create a counter to keep track of the number of digits.

3. Iterate over each character in the string and use a built-in method to check if it's a digit.

4. If it is a digit, increment the counter.

5. After the loop, report the total count of digits.

3. Code Program

# Define the string
input_string = "There are 24 hours in 1 day."

# Initialize the digit count
digit_count = 0

# Loop through the string to count the digits
for char in input_string:
    if char.isdigit():
        digit_count += 1

# Print the count of digits
print(f"The number of digits in the string is: {digit_count}")

Output:

The number of digits in the string is: 3

Explanation:

1. input_string is the string that we will be scanning for digits.

2. digit_count serves as our counter, starting at 0.

3. A for loop is used to go over each character char in input_string.

4. The isdigit() method checks if char is a digit.

5. Whenever isdigit() returns True, digit_count is incremented by 1.

6. Once all characters have been checked, digit_count contains the total number of digits found in input_string.

7. Finally, the print statement is used to display the count of digits, which is 3 for the given input_string.

Comments