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 InputStream
Python Set add()
Python Dictionary items()
Python String format_map()
Python Program to Display Powers of 2 Using Anonymous Function
How to Get Started With Python?
Convert Character Array to String in Java
Python next()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Check Whether a String is Palindrome or Not
Python Program to Randomly Select an Element From the List
Python List reverse()
Python time Module
Python bool()
Count Occurrences of a Char in a String
Python String isidentifier()
Python Program Read a File Line by Line Into a List
Python Program to Find the Square Root
Python String rpartition()
Python String join()
Python Multiple Inheritance
Intelligent Projects Using Python - Santanu Pattanayak
Python String isdigit()
String Hashing
Python Program to Make a Simple Calculator
Python strptime()
Python Program to Print Colored Text to the Terminal
Python Program to Merge Mails
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Keywords and Identifiers
Python Get Current time