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 dir()
Machine Learning with Python for everyone - Mark E.Fenner
Introduction to Scientific Programming with Python - Joakim Sundnes
Python bytes()
Python String center()
Python Data Types
Python Program to Get the File Name From the File Path
Python Program to Display the multiplication Table
Python String encode()
Python Global, Local and Nonlocal variables
Python open()
Python Program to Copy a File
CharSequence vs. String in Java
Python hasattr()
String Hashing
Python list()
JavaScript Methods of RegExp and String
Python all()
Python Program to Capitalize the First Character of a String
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python String istitle()
Python Program to Access Index of a List Using for Loop
Python Dictionary setdefault()
Count Occurrences of a Char in a String
Python String ljust()
Python timestamp to datetime and vice-versa
Python Program to Get File Creation and Modification Date
String Set Queries
Generate a String
Python List insert()
Python Program to Sort a Dictionary by Value
Python String rfind()