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 String rpartition()
Python Program to Merge Mails
Map to String Conversion in Java
Python Program to Find the Size (Resolution) of a Image
Python Program to Randomly Select an Element From the List
Python List
Java Program to Permute All Letters of an Input String
Python id()
Python List Comprehension
How to Get Started With Python?
Python Program to Find Armstrong Number in an Interval
Python Program to Find ASCII Value of Character
Python Operator Overloading
Python List index()
Python Dictionary values()
Python bytearray()
Convert Character Array to String in Java
Python Program to Capitalize the First Character of a String
Python String startswith()
Python open()
Python callable()
Debug a JavaMail Program
Python Data Structures and Algorithms - Benjamin Baka
Python Tuple
Python Program to Convert Celsius To Fahrenheit
Python Program to Iterate Through Two Lists in Parallel
Python Generators
Python getattr()
Python sleep()
Python String isalnum()
Machine Learning with Python for everyone - Mark E.Fenner
Python Tuple count()