String count()

Python String count() method returns the number of occurrences of a specified value in a string.

In this tutorial, we will learn the syntax and examples for count() method of String class.

Syntax

The syntax of String count() method in Python is

</>
Copy
str.count(value, start, end)

where

ParameterRequired/
Optional
Description
valueRequiredA string. The number of occurrences of this value is counted.
startOptionalAn integer. The index from which, the value has to be searched in this string.
endOptionalAn integer. The index until which, the value has to be searched in this string.

Example

In this example, we will take a string 'abcdefabcdef', and find the number of occurrences of the value 'bc'.

Python Program

</>
Copy
x = 'abcdefabcdef'
value = 'bc'
result = x.count(value)
print(f'Number of occurrences is : {result}')

Output

Number of occurrences is : 2

Explanation

'abcdefabcdef'
  bc    bc    : total 2 occurrences

count() with Specific Start

In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen.

Python Program

</>
Copy
x = 'abcdefabcdef'
value = 'bc'
start = 5
result = x.count(value, start)
print(f'Number of occurrences is : {result}')

Output

Number of occurrences is : 1

Explanation

'a b c d e f a b c d  e  f'
 0 1 2 3 4 5 6 7 8 9 10 11
           |
           start=5 from this position
               b c          : total 1 occurrence

count() with Specific Start and End

In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen and the end position up until which the search for value in the string has to happen.

Python Program

</>
Copy
x = 'abcd-abcd-abcd'
value = 'bc'
start = 5
end = 10
result = x.count(value, start, end)
print(f'Number of occurrences is : {result}')

Output

Number of occurrences is : 1

Explanation

'a  b  c  d  -  a  b  c  d  -  a  b  c  d'
 0  1  2  3  4  5  6  7  8  9 10 11 12 13
                |              |
             start=5         end=10
                   b  c           : total 1 occurrence

Conclusion

In this Python Tutorial, we learned how to count number of occurrences of a value in given string using String method – count().