EN
Python - count character occurrences
0 points
In this article, we would like to show you how to count character occurrences in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABCBA"
2
result = text.count("A")
3
4
print(result) # 2
Syntax:
xxxxxxxxxx
1
str.count(substring)
Where:
substring
- Required argument. The string we search for.
Example:
In this example, we use count()
method to count the number of the "A
" character occurrences in the text
string.
xxxxxxxxxx
1
text = "ABCBA"
2
result = text.count("A")
3
4
print('The number of "A" characters: ', result) # 2
Output:
xxxxxxxxxx
1
The number of "A" characters: 2
Syntax:
xxxxxxxxxx
1
str.count(substring[, start[, end]])
Where:
start
- Optional argument. The index from which to start counting (by default start of the string, index 0).end
- Optional argument. The end index for the search (by default end of the string).
Example:
In this example, we use the count()
method with optional arguments to count the number of the "A
" character occurrences in the text
string between index 2
and the end of the string (by default).
xxxxxxxxxx
1
text = 'ABCBA'
2
result = text.count('A', 2, )
3
4
print('The number of "A" characters: ', result) # 1
Output:
xxxxxxxxxx
1
The number of "A" characters: 1