What's the simplest way to count the number of occurrences of a character in a string?

e.g. count the number of times 'a' appears in 'Mary had a little lamb'
Dec 28, 2020 in Python 13,495 views

## 3 answers to this question.

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

```>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')```
• 65,910 points

Another way could be:

Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string.

Examples:

```Input : str = "endtoend"
c = 'e'
Output : 2
'e' appears four times in str.

Input : str = "abccdefgaa"
c = 'a'
Output : 3
'a' appears three times in str.```

 ```// C++ program to count occurrences of a given // character #include #include using namespace std; // Function that return count of the given // character in the string int count(string s, char c) { // Count variable int res = 0; for (int i=0;i
answered Dec 28, 2020 by Nikita

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

answered Dec 28, 2020 by Carlos

+1 vote

## I am trying to write a program in python for the occurrences of a character given the start and stop values of that string only using while

Here's the code: check = input("Enter the character: ...READ MORE

## Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

## How to count the number of elements in a list?

To count the number of elements of ...READ MORE

## What is the Python logic to count the number of capital letters in a file?

Hi, You can use this piece of code, ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

## Lowercase in Python

You can simply the built-in function in ...READ MORE

+1 vote