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:
Check If a String Is Numeric in Java
Python String isalnum()
Python Tuple count()
Python String isidentifier()
Python String splitlines()
Convert String to int or Integer in Java
Python Set symmetric_difference_update()
Python next()
Python Objects and Classes
Python Program to Find the Size (Resolution) of a Image
Jackson – Marshall String to JsonNode
Python *args and **kwargs
Java String Conversions
Python staticmethod()
Check if a String is a Palindrome in Java
Python String index()
Python Program to Find Armstrong Number in an Interval
Python help()
Java Program to Permute All Letters of an Input String
Python sum()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python property()
Python List extend()
Python Program to Find LCM
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String isalpha()
Python Program to Find Numbers Divisible by Another Number
Python String ljust()
Python String startswith()
Python Program to Check Leap Year
Python Program to Check If a List is Empty
CharSequence vs. String in Java