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 Global Keyword
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Java – Reader to String
Python Program to Find ASCII Value of Character
Python Errors and Built-in Exceptions
Python String isalpha()
Python Set add()
Split a String in Java
String Set Queries
Python *args and **kwargs
Python String maketrans()
Python Program to Compute the Power of a Number
Debug a JavaMail Program
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python range()
Python Closures
Python String split()
Python Program to Find the Square Root
Python String isidentifier()
Python complex()
Python Data Structures and Algorithms - Benjamin Baka
Python Variables, Constants and Literals
Python String capitalize()
Python String join()
Python Decorators
Python Program to Create a Long Multiline String
Reading an HTTP Response Body as a String in Java
Python Program to Display the multiplication Table
Python next()
Python any()
Python String lower()
Python ord()