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 Get File Creation and Modification Date
Python abs()
Python Program to Display the multiplication Table
Python List reverse()
Python chr()
Python hash()
Python Recursion
Python Program to Find the Factors of a Number
Python repr()
Python Program to Sort a Dictionary by Value
Python filter()
Python Program to Find ASCII Value of Character
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python staticmethod()
Python Variables, Constants and Literals
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Java InputStream to String
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Debug a JavaMail Program
Python Global, Local and Nonlocal variables
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Convert String to Datetime
Python *args and **kwargs
Python Deep Learning Cookbook - Indra den Bakker
Format ZonedDateTime to String
Python Matrices and NumPy Arrays
Deep Learning with Python - Francois Chollet
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python len()
Python String find()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants