Table of Contents
In this example, you will learn to count the number of occurrences of a character in a string.
To understand this example, you should have the knowledge of the following Python programming topics:
1. 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.
2. 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.
Related posts:
Python Program to Count the Occurrence of an Item in a List
Python Program to Merge Mails
Python Object Oriented Programming
Python Program to Add Two Matrices
Python help()
JavaScript Methods of RegExp and String
Python Program to Convert Decimal to Binary Using Recursion
Python next()
Check if a String is a Palindrome in Java
Python frozenset()
Python hex()
Python Program to Print all Prime Numbers in an Interval
Python str()
Python String rjust()
Python Tuple index()
JavaScript Eval: run a code string
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Find Numbers Divisible by Another Number
Python divmod()
Python Sets
Python List
JavaScript Character classes
Python timestamp to datetime and vice-versa
Python eval()
Java – Reader to String
Python Program to Safely Create a Nested Directory
Converting a Stack Trace to a String in Java
Python String isalnum()
Python Set discard()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Find Factorial of Number Using Recursion
Python slice()