The count()
method helps find the number of occurrences of subsequence in the specified range containing the start and end index. The start and end parameters are optional and deduced as slice notation.
str.count(sub, start = 0, end = len(string))
sub
: Represents the subsequence that is to be searched.start
: The index for starting the search. The index of the first character is 0
. The default value of the start parameter is 0
.end
: Represents the ending index of the search. Its value is the last index.This method returns the number of occurrences of subsequence in the defined binary data or bytes-like object.
In the code snippet below, we will use this method to search sub-strings from the parent string:
str = "01011101 01110101"# COUNT NUMBER OF 0'ssub = '0'print ("str.count('0') : ", str.count(sub))# COUNT NUMBER OF 1's from 1 to 8# IT WILL RETURN COUNT FROM 1 TO LESS THAN 8sub = '1'print ("str.count('str', 1, 8) : ", str.count(sub,1,8))
str
. We can use a sub-string to argue the count()
method.str
by using count()
from 1st
position to 8th
.bytes.count(sub[, start[, end]])
sub
ranges between start
and end
.count()
method must be a byte
object like “abc” string or a “c” string literal or a number between 0 and 255.start
and end
arguments are optional.This method returns the number of occurrences.
bytearray.count(sub[, start[, end]])
sub
ranges between start
and end
.count()
must be a bytearray
object, like “abc” string or a “c” string literal or a number between 0 and 255.start
and end
arguments are optional.This method returns the number of occurrences.
The code snippet below demonstrates the use of the count()
method from bytes
and bytearray
classes:
# Create a bytes object and a bytearray.# bytes type objectdata = bytes(b"aabbbccc")# bytearray type objectarr = bytearray(b"aabbcccc")# The count method works on both.print("Count of c: ", data.count(b"c"))print("Count of c: ", arr.count(b"c"))
bytes
type instance.bytearray
type instance.count()
function to check the number of occurrences of the specified argument value i.e., the character c
.