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:
Java – String to Reader
Python Program to Return Multiple Values From a Function
Python String partition()
Map to String Conversion in Java
Python String rsplit()
Python String encode()
Python String format_map()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Deep Learning with Python - Francois Cholletf
Python property()
Python Inheritance
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Check Leap Year
Python max()
Python Multiple Inheritance
Python bin()
Python String replace()
Python Tuple index()
Python Namespace and Scope
JavaScript Eval: run a code string
Python Program to Check If Two Strings are Anagram
Python Program to Count the Occurrence of an Item in a List
Python Program to Access Index of a List Using for Loop
Python hex()
How to Remove the Last Character of a String?
Python String rpartition()
Python Program to Find the Sum of Natural Numbers
Python Program to Shuffle Deck of Cards
Python iter()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Convert Character Array to String in Java
Python Exception Handling Using try, except and finally statement