Home >Backend Development >Python Tutorial >How Can I Count Character Occurrences in a Python String?
Determining Character Occurrences in a String
Counting the number of times a specific character appears in a string is a common programming task. In Python, this can be accomplished using the str.count() method.
Solution:
The str.count() method takes three optional arguments:
To count the occurrences of a character, simply call the count() method with the character as the argument. For example:
sentence = 'Mary had a little lamb' char_count = sentence.count('a')
This code assigns the count of 'a' in the string to the variable char_count. The output is:
4
Additional Notes:
char_count = sentence.count('a', 0, len(sentence) // 2)
The above is the detailed content of How Can I Count Character Occurrences in a Python String?. For more information, please follow other related articles on the PHP Chinese website!