Python Program to Count the Number of Occurrence of a Character in String

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using a for loop

count = 0

my_string = "Programiz"
my_char = "r"

for i in my_string:
    if i == my_char:
        count += 1

print(count)

Output

2

In the above example, we have found the count of 'r' in 'Programiz'. The for-loop loops over each character of my_string and the if condition checks if each character of my_string is 'r'. The value of count increases if there is a match.


Example 2: Using method count()

my_string = "Programiz"
my_char = "r"

print(my_string.count(my_char))

Output

2

count() counts the frequency of the character passed as parameter.


Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to find the first letter in a string that occurs only once.

  • Return an empty string if no such character exists.
  • For example, for input "Hello World", the output should be "H".
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges