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 Statement, Indentation and Comments
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Find Armstrong Number in an Interval
Python Program to Calculate the Area of a Triangle
String Hashing
Python *args and **kwargs
Python Program to Differentiate Between type() and isinstance()
Python Object Oriented Programming
Python Program to Create a Long Multiline String
Python ord()
Python pow()
Python String isdecimal()
Python Set copy()
Python String title()
Python Program to Safely Create a Nested Directory
Python bool()
Intelligent Projects Using Python - Santanu Pattanayak
Python String isidentifier()
Python Program to Remove Duplicate Element From a List
Python min()
Python Dictionary
Python Directory and Files Management
Python Tuple index()
Python Program to Print Colored Text to the Terminal
Python List
Java String to InputStream
Python eval()
Python open()
Python type()
Convert String to Byte Array and Reverse in Java
Python slice()
Python Program to Reverse a Number