count occurrences of each character in string python code example

Example 1: python count character occurrences

str1.count("a")

Example 2: how to count the occurrence of a word in string python

# define string
string = "Python is awesome, isn't it?"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

Example 3: python codes for counting the occurrence of a letters in dictionary excluding digits

def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

Tags:

Java Example