Python string count() method

The Python string count() returns the number of non-overlapping repetitions of a character or series of characters in the given string. Passing the parameters start and end to the method count(), part of the string is obtained to perform the count.

Syntax:

string_var.count(substring [, start [, end]])

This count() method accepts three parameters.

substring A string to be searched in the specified string.
start(Optional) The position of the character where the string is to be sliced to start the count. The default position is 0.
end(optional) The character's position where the count is to be finished. The default position is the end of string.
Return Value:

The count() returns the number of non-overlapping repetitions of a character or series of characters in the given string.

			

# Python example of the count() method, with the only first parameter.

stext = "tutorialsnation.com is the best for learning Python"
# number of repetition of character 'o'
print('Number of repetitions of character o:', stext.count('p'))


				

Output:

Number of repetitions of p: 5
			

<p>The above example shows five, the character o appears five times in the string.</p>

<div class="code-view">
		<pre>
			<code class="language-python">
<xmp>
# Python example of the count() method, with the start and end parameter.

stext = "tutorialsnation.com is the best for learning Python"
# number of repetition of character 'o'
print('Number of repetitions of character o:', stext.count('p', 3, 20))


				

Output:

Number of repetitions of p: 3

The above example shows three, the character o has appeared three times between positions 3 and 20 in the string.