Att String Count
## Python String count() Method
The `count()` method is a built-in Python string method used to count the number of occurrences of a specific substring within a string. It also allows you to narrow down the search by specifying optional start and end index boundaries.
---
## Description
The `count()` method searches the target string and returns the total number of non-overlapping occurrences of the specified substring. You can optionally restrict the search to a specific slice of the string using the `start` and `end` parameters.
---
## Syntax
```python
str.count(sub, start=0, end=len(string))
```
### Parameters
* **`sub`**: The substring (or single character) you want to search for and count.
* **`start`** *(Optional)*: The starting index where the search begins. The default is `0` (the beginning of the string).
* **`end`** *(Optional)*: The ending index where the search stops. The default is the end of the string. Note that the character at the `end` index is **not** included in the search range (it is exclusive).
### Return Value
* Returns an **integer** representing the number of times the substring appears in the specified range.
* If the substring is not found, it returns `0`.
---
## Code Examples
### Basic Usage
The following example demonstrates how to use the `count()` method with and without index boundaries:
```python
# Define a sample string
text = "this is string example....wow!!!"
# Example 1: Count occurrences of a single character 'i' within a specific range
sub_char = "i"
# Search from index 4 to 40
count_range = text.count(sub_char, 4, 40)
print(f"text.count('{sub_char}', 4, 40) : {count_range}")
# Example 2: Count occurrences of a substring 'wow' in the entire string
sub_word = "wow"
count_all = text.count(sub_word)
print(f"text.count('{sub_word}') : {count_all}")
```
### Output
```text
text.count('i', 4, 40) : 2
text.count('wow') : 1
```
---
## Important Considerations
### 1. Case Sensitivity
The `count()` method is case-sensitive. Searching for `"apple"` will not count occurrences of `"Apple"` or `"APPLE"`.
```python
text = "Apple, apple, APPLE"
print(text.count("apple")) # Output: 1
```
### 2. Non-Overlapping Matches
The method only counts **non-overlapping** occurrences. If characters overlap, they are not counted twice.
```python
text = "banana"
# Searching for "ana"
print(text.count("ana")) # Output: 1
# Explanation: The first "ana" is found at index 1-4 ("bna").
# The remaining part is "na", which does not match "ana".
```
### 3. Negative Indexing
You can use negative integers for the `start` and `end` parameters to count from the end of the string.
```python
text = "apple-apple-apple"
# Search in the last 11 characters
print(text.count("apple", -11)) # Output: 2
```
YouTip