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().
s="hello world"res=s.count("o")print(res)
2
Explanation: The letter "o" appears twice in the string "hello world", so count() returns 2.
Table of Content
string.count(substring, start = 0, end = len(s))
Here are a few examples ofcount() method for better understanding.
s="Python is fun and Python is powerful."print(s.count("Python"))
s="GeeksforGeeks"print(s.count("e"))
4
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)
1
Explanation: We set start=1 andend=20, socount()method will search for "apple" from the beginning up to index 20.
Related Articles:
S
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers