The Wayback Machine - https://web.archive.org/web/20240927070641/https://www.geeksforgeeks.org/python-string-count-method/
Open In App

Python String count() Method

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python String count() function returns the number of occurrences of a substring within a String.

Python3




#initializing a string
my_string = "Apple"
#using string count() method
char_count = my_string.count('A')
#printing the result
print(char_count)


Output

1

In this article, we will explore the details of the count() method, exploring its syntax, usage, and some practical examples.

What is the String count() Method?

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

It is a very useful string function that can be used for string analysis.

Note: string count() function is case sensitive, meaning it will treat ‘a’ and ‘A’ different.

String count() Method Syntax

string. Count(substring, start= …., end= ….)

Parameters: 

  • The count() function has one compulsory and two optional parameters. 
    • Mandatory parameter: 
      • substring – string whose count is to be found.
    • Optional Parameters: 
      • start (Optional) – starting index within the string where the search starts. 
      • end (Optional) – ending index within the string where the search ends.

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

Example:

Python3




#initializing a string
my_string = "Banana"
#using string count() method
char_count = my_string.count('a')
#printing the result
print(char_count)


Output

3

How to use String count() Method

String count() method is very simple and straightforward to use. You just need to pass the substring as the parameter in function to count it’s number of occurrence. Let’s understand how to count string in Python with an example.

More Example on String count() Method

Let us see a few examples of the Python String count() method.

Python3




my_string = "GeeksForGeeks"
char_count = my_string.count('e')
print(char_count)


Output

4

Below are some examples by which we can count the number of occurence of a substring in python:

  • Count Occurrences of a given Substring
  • Count Occurrences of Character in Multiple String
  • Using Regular Expression
  • Using Start and End Parameter

1. Using String Count() to Count Occurrences of a given Substring

In this example, Python String Count() will count the occurrences of a given substring and pass only one argument which is mandatory, and skip the optional arguments. We can use it to count the number of occurence of a substring in python

Python3




# string in which occurrence will be checked
string = "geeks for geeks"
 
# counts the number of times substring occurs in
# the given string and returns an integer
print(string.count("geeks"))


Output

2

Time Complexity: O(n)
Auxiliary Space: O(1)

2. Using String Count() to Count Occurrences of Character in Multiple String

In this example, Python String Count() will count the occurrences of characters in multiple strings.

Python3




strings = ["Red", "Green", "orange"]
char_to_count = 'e'
total_count = sum(string.count(char_to_count) for string in strings)
print(total_count)


Output

4

Time Complexity: O(m*k)
Auxiliary Space: O(k)

3. Using String count() Method with Regular Expression

In this example, Python String Count() will count the occurrences of single character in the string using Regular Expression.

Python3




import re
 
my_string = "Good Morning and Morning is Great."
substring = "Morning"
substring_count = len(re.findall(substring, my_string))
print(substring_count)


Output

2

Time Complexity: O(m)
Auxiliary Space: O(1)

4. Using String count() Method with Start and End Parameter

In this example, Python String Count() will count the occurrences of a given string using Start and end parameters and pass all three arguments to find the occurrence of a substring in a Python String.

Python3




# string in which occurrence will be checked
string = "geeks for geeks"
 
# counts the number of times substring occurs in
# the given string between index 0 and 5 and returns
# an integer
print(string.count("geeks", 0, 5))
 
print(string.count("geeks", 0, 15))


Output

1
2

Time Complexity: O(n)
Auxiliary Space: O(1)

In this article we have covered the definition, syntax and examples of Python string count() method. We have explained the working of string count() function with variations in use cases. String count() method is very important function for string operations.

Read Other Python String Methods

Similar Articles:



Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python | Count and display vowels in a string
In this program, we need to count the number of vowels present in a string and display those vowels. This can be done using various methods. In this article, we will go through few of the popular methods to do this in an efficient manner. Examples: In a simple way Input : Geeks for Geeks Output : 5 ['e', 'e', 'o', 'e', 'e'] This is in a different w
6 min read
Python | Count all prefixes in given string with greatest frequency
Given a string, print and count all prefixes in which first alphabet has greater frequency than second alphabet.Take two alphabets from the user and compare them. The prefixes in which the alphabet given first has greater frequency than the second alphabet, such prefixes are printed, else the result will be 0. Examples : Input : string1 = "geek", a
4 min read
Python | Count occurrences of a character in string
Given a string, the task is to count the frequency of a single character in that string using Python. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. Example Input:'GeeksForGeeks'Output:'4'Explanation: In this, we have counted the occurrence of 'e' in the string.
6 min read
Count the number of unique characters in a string in Python
Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: S = "geeksforgeeks" Output: 7 Explanation: The given string "geeksforgeeks" contains 6 unique characters {'g', 'e', 'k', 's', 'f', 'o', 'r'}.Input: S = "madam" Output: 3 Approach: The idea to solve
5 min read
Python | Count the Number of matching characters in a pair of string
Given a pair of non-empty strings. Count the number of matching characters in those strings (consider the single count for the character which have duplicates in the strings). Examples: Input : str1 = 'abcdef' str2 = 'defghia'Output : 4 (i.e. matching characters :- a, d, e, f)Input : str1 = 'aabcddekll12@' str2 = 'bb2211@55k'Output : 5 (i.e. matchi
4 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Python | sympy.count() method
Using the count() method in the sympy module, we can count the number of variables used in the mathematical function. count() method returns the number of variables used in the mathematical function. Syntax : sympy.count(x) Return : the count of variables. Code #1: With the help of the below examples, we can clearly understand that using sympy.coun
1 min read
Python List count() method
Python List count() method returns the count of the occurrences of a given element in a list. Example: C/C++ Code #create a list fruits = ["Apple", "Mango", "Banana", "Cherry" , "Papaya"] # printing count using count() function print(fruits.count("Apple")) Output1 What is the list count()
4 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isalpha() Method
Python String isalpha() method is used to check whether all characters in the String are an alphabet. Python String isalpha() Method SyntaxSyntax: string.isalpha() Parameters: isalpha() does not take any parameters Returns: True: If all characters in the string are alphabet.False: If the string contains 1 or more non-alphabets.Errors and Exceptions
4 min read
Python String isprintable() Method
Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 )Uppercase letters ( ABC
3 min read
Python String isdigit() Method
Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”. Python String isdigit() Method Syntax Syntax: string.isdigit() Parameters: isdigit() does not take any parameters Returns: True - If all characters in the string are digits.False - If the string contains 1 or more non-digits. Tim
3 min read
Python String isnumeric() Method
The isnumeric() method is a built-in method in Python that belongs to the string class. It is used to determine whether the string consists of numeric characters or not. It returns a Boolean value. If all characters in the string are numeric and it is not empty, it returns “True” If all characters in the string are numeric characters, otherwise ret
3 min read
Python String splitlines() Method
Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional). Syntax: string.splitlines([keepends]) Parameters: keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position
2 min read
Python String center() Method
Python String center() method creates and returns a new string that is padded with the specified character. Syntax: string.center(length[, fillchar]) Parameters: length: length of the string after padding with the characters.fillchar: (optional) characters which need to be padded. If it's not provided, space is taken as the default argument. Return
2 min read
Python String istitle() Method
Python String istitle() Method is a built-in string function that returns True if all the words in the string are title cased, otherwise returns False. Python String istitle() Method Syntax Syntax: string.istitle() Returns: True if the string is a title-cased string otherwise returns False. Python String istitle() Method Example C/C++ Code string =
2 min read
Python string isdecimal() Method
Python String isdecimal() function returns true if all characters in a string are decimal, else it returns False. In this article, we will explore further the isdecimal() method, understand its functionality, and explore its practical applications in Python programming. Python String isdecimal() SyntaxSyntax: string_name.isdecimal(), string_name is
2 min read
Python String isalnum() Method
Python String isalnum() method checks whether all the characters in a given string are either alphabet or numeric (alphanumeric) characters. Python String isalnum() Method Syntax: Syntax: string_name.isalnum() Parameter: isalnum() method takes no parameters Return: True: If all the characters are alphanumeric False: If one or more characters are no
1 min read
Python string swapcase() Method
Python String swapcase() method converts all uppercase characters to lowercase and vice versa of the given string and returns it. Syntax: string_name.swapcase() Parameter: The swapcase() method does not take any parameter. Return Value: The swapcase() method returns a string with all the cases changed. Example Below is the Python implementation of
1 min read
Article Tags :
Practice Tags :