Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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'

1 Answer

0 votes
by (106k points)

In Python, we have a function str.count() which tells the number of count of any character in a string:-

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

It returns 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.

Below is an example that shows you how it works:-

sentence = 'Mary had a little lamb'

sentence.count('a') 

image

 

 

 

 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

Browse Categories

...