Movatterモバイル変換


[0]ホーム

URL:


Open In App

Thecount()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 usingcount().

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

Output
2

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

  • substring (required):The substring we want to count within the original string.
  • start (optional):The index position in the string where the search should begin. Default is0.
  • end (optional):The index position in the string where the search should stop. Default is the length of the string (i.e., up to the end).

Return Type

  • Thecount() method returns an integer representing the number of times the specified substring appears within the given range of the string.

Example of count() Method

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

Counting Words in String

Python
s="Python is fun and Python is powerful."print(s.count("Python"))

Output
2

Finding Character Frequency in String

Python
s="GeeksforGeeks"print(s.count("e"))

Output
4

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 rangeres=s.count(substring,1,20)print(res)

Output
1

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

Related Articles:


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp