isalpha(): To check if a string/character is an alphabet
isdigit(): To check if a string/character is a digit.
Solution;
Iterate each character from a string using a for loop
In each loop iteration, check if the current character is the alphabet using an isalpha() function. If yes, increase the character counter. Check if it is a digit using the isdigit() function and increase the digit counter; otherwise, increase the symbol counter.
Print the value of each counter
def find_digits_chars_symbols(sample_str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1
print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)
sample_str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)
Hint:
Use the following string functions
isalpha()
: To check if a string/character is an alphabetisdigit()
: To check if a string/character is a digit.Solution;
for
loopisalpha()
function. If yes, increase the character counter. Check if it is a digit using theisdigit()
function and increase the digit counter; otherwise, increase the symbol counter.