Python String count() Method

20-02-23 Ahmed Obaid 2117 0

​The count() function returns the number of occurrences of the substring passed to the parameter. The count() function takes three parameters, the first is a substring, the second is the starting index and the third is the last pointer of the range. Beginning and ending are both optional while the substring is required.


How to formulate it like this:


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

Parameters:


  • Substring : (Required) The string whose number of occurrences you want to find.

  • start : (optional) the starting index within the string from which the search begins.

  • End : ( Optional ) The index of the end within the string that the search ends with.

Return value: The count() function returns an integer indicating the number of occurrences of a substring in a given string.


We will use the count() function without the optional ( start ) and ( end ) parameters. We'll just use the substring parameter to find the number of occurrences of a given string.

In the following example we will search for the number of occurrencesundefined The substring represented by the letter (a),

 Example:


 # String to check for duplicates
 string = "learn python With ahmed obaid"
 # Searches the given string for duplicate substrings and returns an integer
 print(string. count("a"))

 The output will be:


 3

 In the following example, we will search for the number of occurrences of the substring represented by the word (of).


 # String to check for duplicates
 string = "The number of occurrences of the substring in the input string"
 # Searches the given string for duplicate substrings and returns an integer
 print(string. count("of"))

 The output will be:


 2

 In the following example, we will use the count() function with optional (start) and (end) parameters.

 Example:


 # String to check for duplicates
 string = "The number of occurrences of the substring in the input string"
 # Counts the number of occurrences of the substring
 # Searches the specified string The specified string between index 0 and 15 and returns an integer
 print(string. count("of", 0, 15)) # returns 1
 # Search the specified string The specified string is between index 0 and 48 and returns an integer
 print(string. count("of", 0, 48)) # returns 2

 The output will be:


 1
 2

 External sources:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python python data types Python String string methods python String search functions in Python python string count method

Share page