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 isdigit()
Array to String Conversions
Python float()
Python List remove()
Python Exception Handling Using try, except and finally statement
Python String rjust()
Python Program to Get the Full Path of the Current Working Directory
Java InputStream to String
Python Tuple
Guide to Character Encoding
Python frozenset()
Python hex()
Python strftime()
Python Program to Get Line Count of a File
Java – Generate Random String
Python List
Python Program to Print Colored Text to the Terminal
Python Program to Find LCM
Java – String to Reader
Python reversed()
Python String isidentifier()
Python getattr()
Python issubclass()
Python Global Keyword
Python Strings
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python List append()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python List Comprehension
Python Dictionary setdefault()
Python Program to Compute the Power of a Number
Python super()