gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
count number of digits in a string
- User
count number of digits in a string
- Assistant
To count the number of digits in a string, you can iterate through each character in the string and check if it is a digit. Here’s how you can do it in Python:
pythondef count_digits(s): return sum(c.isdigit() for c in s) # Example usage string = "Hello 12345, it's 2023!" num_digits = count_digits(string) print("Number of digits in the string:", num_digits)In this code:
- We define a function called
count_digitsthat takes a stringsas an argument. - We use a generator expression inside the
sumfunction to count how many characters in the string are digits using theisdigit()method. - Finally, we print the total count of digits found in the string.
You can use this function with any string to get the count of digits.
- We define a function called