AppDividend
Latest Code Tutorials

Python String Count Example | String.count() Tutorial

0 16

Get real time updates directly on you device, subscribe now.

Python String Count Example | String.count() Tutorial is today’s topic. Python string count() method returns the number of occurrences of the substring in the given string. Python count() method searches the substring in the given string and returns how many times the substring is present in it. It also takes optional parameters to start and end to specify the starting and ending positions in the string respectively.

Python String Count Example

The syntax of count() method is following.

string.count(substring, start, end)

The count() function has one compulsory and two optional parameters.

The substring is a required parameter which is a string whose count is to be found. 

The start parameter is an Optional which is the starting index within the string where the search starts. 

The end parameter is an Optional which is the ending index within the string where the search ends.

Python String count() method returns an integer that denotes the number of times a substring occurs in a given string.

See the following example.

# app.py

friend = 'What did you bring Mr. Bing'
substring = 'ing'
count = friend.count(substring)
print('The substring occurs {} times'.format(count))

Here, we have used the ing as a substring and check how many times it is repeated inside the String. Also, we have used the String Format to format the string. See the following output.

 

Python String Count Example

Use the Start and End parameter

Let’s take an example where we pass a start and end parameter.

# app.py

friend = 'What did you bring Mr. Bing'
substring = 'ing'
count = friend.count(substring, 11, 18)
print('The substring occurs {} times'.format(count))

See the output of the above example.

 

Use the Start and End parameter

It will count the number of substrings between the 11th and 18th index characters. In our example, ing occurs only one time between that characters that is why we see the one time.

Python count() function in an inbuilt function in a python programming language that returns the number of occurrences of the substring in the provided string.

Finally, Python String Count Example | String.count() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.