Editor

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

  1. The loop compares each character ch of text with the chosen char.
  2. Every match adds one to count, which starts at 0.
  3. The comparison is case-sensitive, so "M" and "m" are counted separately; use text.lower() to count both.
  4. If the character never appears, the loop finishes with count still 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.

All Python programs · CBSE class 12 practical file · Python exercises