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

Write a python program to count occurrences of all characters within a string
Q:

Write a python program to count occurrences of all characters within a string

0

Write a program to count occurrences of all characters within a string

Given:

str1 = "Apple"

Expected Outcome:

{'A': 1, 'p': 2, 'l': 1, 'e': 1}

All Answers

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

Hint:

Use the string function count()

Solution:

  • create an empty dictionary to store the result. character is the key, and the count is the value
  • Iterate each character from a string s1 using a loop
  • In the body of a loop, use the count() function to find how many times a current character appeared in a string
  • Add key-value pair in a dictionary
str1 = "Apple"

# create a result dictionary
char_dict = dict()

for char in str1:
    count = str1.count(char)
    # add / update the count of a character
    char_dict[char] = count
print('Result:', char_dict)

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