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 Print Output Without a Newline
Python Iterators
Python super()
Python List
Intelligent Projects Using Python - Santanu Pattanayak
Python any()
Python String join()
Python divmod()
Python String istitle()
CharSequence vs. String in Java
Python iter()
Python Program to Merge Mails
Python String rfind()
Python Generators
Python Program to Convert Two Lists Into a Dictionary
Python enumerate()
Python *args and **kwargs
Python Shallow Copy and Deep Copy
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Set clear()
Deep Learning in Python - LazyProgrammer
Python del Statement
Python Object Oriented Programming
Case-Insensitive String Matching in Java
Python issubclass()
Python Program to Get the Full Path of the Current Working Directory
Python getattr()
Python id()
Python String zfill()
Python Program to Compute the Power of a Number
Array to String Conversions
Python Variables, Constants and Literals