A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now