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 Solve Quadratic Equation
Python String title()
Intelligent Projects Using Python - Santanu Pattanayak
Python len()
Python String rjust()
Python String lower()
Python Program to Get the File Name From the File Path
Python String strip()
Python Set symmetric_difference()
Python bytes()
Python Tuple count()
Python Program to Get File Creation and Modification Date
Python Operators
Python Program to Create a Long Multiline String
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Multiply Two Matrices
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String splitlines()
Python range()
Python globals()
Python String maketrans()
Python List sort()
Python Set union()
Python Get Current time
Python *args and **kwargs
Python String partition()
How to Remove the Last Character of a String?
Python Set issuperset()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program Read a File Line by Line Into a List
Encode a String to UTF-8 in Java