Python str.count() function
str.count()
Function in Python
The str.count()
function in Python is used to count the number of occurrences of a specified substring within a string. This function is useful for determining how many times a particular substring appears in a string.
Syntax:
substring
: The substring you want to count.start
(optional): The starting index from where the count should begin. The default is0
.end
(optional): The ending index where the count should stop. The default is the end of the string.
Example 1: Basic usage
In this example:
- The substring
"Hello"
appears 2 times in the string.
Example 2: Specifying start and end indices
Here:
- The count of
"a"
is done only within the substring"anan"
(from index 1 to index 5), resulting in 2 occurrences.
Example 3: Case sensitivity
In this case:
- The count of
"hello"
(lowercase) returns 1, while the uppercase"Hello"
is not counted, demonstrating thatstr.count()
is case-sensitive.
Example 4: Counting a substring not present
Here:
- The substring
"Python"
is not found in the original string, so the count returns 0.
Key Points:
str.count()
returns the number of non-overlapping occurrences of the specified substring.- It is case-sensitive, meaning that different cases (uppercase vs. lowercase) are treated as different characters.
- If the substring is not found, it returns 0.
- You can specify optional
start
andend
parameters to limit the search range within the string. - The function does not modify the original string.
Example 5: Counting overlapping substrings
If you want to count overlapping occurrences, you'll need a different approach, as str.count()
does not count overlapping substrings.
In this example:
- The loop counts overlapping occurrences of
"aa"
in the string"aaa"
and outputs 2.