Python Program to Count Occurrences of a Character in a String
Beginner · Strings
This program counts how many times one chosen character appears in a string, for example how many times s appears in "Mississippi". It checks every character in turn and keeps a running count.
Program
count_character_occurrences.py
text = "Mississippi" # or: text = input("Enter a string: ")
char = "s" # or: char = input("Enter a character: ")
count = 0
for ch in text:
if ch == char:
count += 1
print("String:", text)
print(f"'{char}' appears {count} times")
Output
String: Mississippi 's' appears 4 times
How it works
- The loop compares each character
choftextwith the chosenchar. - Every match adds one to
count, which starts at 0. - The comparison is case-sensitive, so "M" and "m" are counted separately; use
text.lower()to count both. - If the character never appears, the loop finishes with
countstill at 0.
Other ways to write it
Using count()
Using count()
text = "Mississippi"
print("s:", text.count("s"))
print("i:", text.count("i"))
print("m, ignoring case:", text.lower().count("m"))
print("ss:", text.count("ss"))
Output
s: 4 i: 4 m, ignoring case: 1 ss: 2
count() does the loop for you, and it can also count longer pieces of text, counting matches that do not overlap.
Find the positions too
Find the positions too
text = "Mississippi"
char = "s"
positions = [i for i, ch in enumerate(text) if ch == char]
print(f"'{char}' appears {len(positions)} times, at positions {positions}")
Output
's' appears 4 times, at positions [2, 3, 5, 6]
enumerate() gives each index with its character, and the list comprehension keeps the indexes where the character matches.
Try it yourself
Count how many times the letter e appears in a sentence of your own, ignoring case.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Frequency of Each Character in a String
- Count Occurrences of an Element in a List
- Find Duplicate Characters in a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises