Q:

Count all letters, digits, and special symbols from a given string using python programming

belongs to collection: Python String Exercises

0

Count all letters, digits, and special symbols from a given string

Given:

str1 = "P@#yn26at^&i5ve"

Expected Outcome:

Total counts of chars, digits, and symbols 

Chars = 8 
Digits = 3 
Symbol = 4

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

Use the following string functions

  • 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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Create a mixed String using the following rules us... >>
<< Arrange string characters such that lowercase lett...