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 String startswith()
Python Recursion
Python if...else Statement
Python filter()
Java Program to Implement the Program Used in grep/egrep/fgrep
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Get the File Name From the File Path
Python Program to Append to a File
Python String swapcase()
Python Program to Get the Class Name of an Instance
Python Objects and Classes
Python Global, Local and Nonlocal variables
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Merge Mails
Convert Character Array to String in Java
Python Program Read a File Line by Line Into a List
Python callable()
Python ascii()
Python Program to Check Whether a String is Palindrome or Not
Python Global Keyword
Python time Module
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python List count()
Python String splitlines()
Python int()
Python abs()
Python Modules
Python String rindex()
Python String maketrans()
Python Anonymous / Lambda Function
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Convert Celsius To Fahrenheit