In: Computer Science
Given a string, such as x = ‘itm330’, write a Python program to count the number of digits and the number of letters in it. For example, in ‘itm330’, there are 3 letters and 3 digits.
Hint: Very similar to page 11 on the slides. To check if a character c is a digit, use c.isdigit(). If c is a digit, c.isdigit() will be a True.
Python code for the problem is provided below, please comment if any doubts:
Note: The indentation may lost when you copy the below code, so refer the screenshot provided at the end to reconstruct the indentation if any such problem occurs
Python Code:
#set the string
x='itm330'
#decalare the counts
numLetters=0
numDigits=0
#The for loop to count the digits and characters
for c in x:
#if character is a digit
if c.isdigit():
#Update the digits
count
numDigits=numDigits+1
#if character is a letter
elif c.isalpha():
#Update the letter
count
numLetters=numLetters+1
else:
pass
#display the result
print("Letters count: ", numLetters)
print("Digits count: ", numDigits)
Output:
Screenshot of the Code: