Q:

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

belongs to collection: Python String Exercises

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)

Python String Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Reverse a given string using python programming... >>
<< Calculate the sum and average of the digits presen...