Count Digits and Letters

Category: Python Basics
Tags:

Write a program to calculate the number of digits and letters in a string. The program should take a string as input and output two integers: the first representing the number of digits and the second representing the number of letters.

Example:

Input: "hello123"
Output: [3, 5]

Input: "2023world"
Output: [4, 5]

You can traverse each character in the string and check if it’s a digit or a letter by using the built-in isdigit() and isalpha() string methods.

def count_digits_letters(s):
digits = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
return [digits, letters]

print(count_digits_letters("hello123")) # Outputs: [3, 5]
print(count_digits_letters("2023world")) # Outputs: [4, 5]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!