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 next()
CharSequence vs. String in Java
Python Program to Get File Creation and Modification Date
Python Namespace and Scope
Python Program to Get Line Count of a File
Python datetime
Python Modules
Python String index()
Check If a String Is Numeric in Java
Python Functions
Python Numbers, Type Conversion and Mathematics
Python Recursion
Python property()
Convert char to String in Java
Python List count()
Python zip()
Python Program to Convert Celsius To Fahrenheit
Python Set issubset()
Python Program to Slice Lists
Python Program to Convert Two Lists Into a Dictionary
Python String splitlines()
Python help()
Python String maketrans()
Convert Character Array to String in Java
Java – String to Reader
Python List clear()
Deep Learning in Python - LazyProgrammer
Python Program to Convert Kilometers to Miles
Python Global, Local and Nonlocal variables
Python setattr()
Python compile()
Python Program to Count the Number of Each Vowel