Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of occurrences of a character in a string

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

e.g. count the number of times that 'a' appears in 'Mary had a little lamb'.

like image 411
Mat Avatar asked Jul 20 '09 20:07

Mat


People also ask

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count occurrences in a string in Python?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

How do you find all occurrences of a character in a string Python?

Use the string. count() Function to Find All Occurrences of a Substring in a String in Python. The string. count() is an in-built function in Python that returns the quantity or number of occurrences of a substring in a given particular string.


2 Answers

str.count(sub[, start[, end]])

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') 4 
like image 123
Ogre Codes Avatar answered Oct 21 '22 10:10

Ogre Codes


You can use count() :

>>> 'Mary had a little lamb'.count('a') 4 
like image 40
eduffy Avatar answered Oct 21 '22 09:10

eduffy