HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Count the number of occurrences of a character in a string

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
theoccurrencescharacternumberstringcount

Problem

How do I count the number of occurrences of a character in a string?

e.g. 'a' appears in 'Mary had a little lamb' 4 times.

Solution

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

Code Snippets

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

Context

Stack Overflow Q#1155617, score: 1865

Revisions (0)

No revisions yet.