Python String count()

In Python, string.count() is used to count the occurrences of a character or a substring in the given input string.

input_string = "how to do in java"
substring = "a"

print( input_string.count(substring) )

Program Output.

2

1. String count() Syntax

The syntax of count() function is:

string.count(substring, start_index, end_index)

1.1. Arguments

Only the substring is required parameter. Start index and end index are optional parameters.

  • substring : whose occurrences needs to be counted in the given string.
  • start_index : from this index location, the search for the substring starts.
  • end_index : in this index location, the search for the substring stops.

1.2. Return Value

The count() method returns the number of occurrences of substring into the give input_string.

2. String count() Examples

Example 1: Counting the number of occurrences of a word in given sentence

In the given program, we are counting how many times “python” word appears in the string.

sentence = "python development is a lot easy with python supported IDEs"
word = "python"

print( sentence.count(word) )

Program Output.

2

Example 2: Counting the occurrences of a word within start and end index

In the given program, we are counting how many times “python” word appears in first 30 characters. The index location for first 30 characters – starts with 0 and ends at 29.

sentence = "Getting started with python is easy. python libs are so useful in AI and ML."
word = "python"

print( sentence.count(word, 0, 29) )

Program Output.

2

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode