A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-string-count-method/ below:

Python String count() Method - GeeksforGeeks

Python String count() Method

Last Updated : 06 Nov, 2024

The count() method in Python returns the number of times a specified substring appears in a string. It is commonly used in string analysis to quickly check how often certain characters or words appear.

Let's start with a simple example of using count().

Python
s = "hello world"
res = s.count("o")
print(res)

Explanation: The letter "o" appears twice in the string "hello world", so count() returns 2.

Syntax of count() Method

string.count(substring, start = 0, end = len(s))

Parameters Return Type Example of count() Method

Here are a few examples of count() method for better understanding.

Counting Words in String Python
s = "Python is fun and Python is powerful."
print(s.count("Python")) 
Finding Character Frequency in String Python
s = "GeeksforGeeks"
print(s.count("e")) 
Count Substring Occurrences with Start and End parameter Python
s = "apple banana apple grape apple"
substring = "apple"

# Using start and end parameters to count occurrences 
# of "apple" within a specific range
res = s.count(substring, 1, 20)  

print(res)

Explanation: We set start=1 and end=20, so count() method will search for "apple" from the beginning up to index 20.

Related Articles:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4