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 id()
Python String isalpha()
Python Tuple
Python String index()
Python Exception Handling Using try, except and finally statement
Python Program to Print all Prime Numbers in an Interval
JavaScript Eval: run a code string
Java InputStream to String
Python String split()
Python Program to Remove Punctuations From a String
Python Deep Learning Cookbook - Indra den Bakker
Python List copy()
Python Program to Count the Number of Digits Present In a Number
Python vars()
Python Program Read a File Line by Line Into a List
Python timestamp to datetime and vice-versa
Python callable()
Python Program to Check Leap Year
Python pow()
Python sleep()
Python for Loop
Python Program to Find Hash of File
Python Program to Create a Long Multiline String
Python Program to Parse a String to a Float or Int
Format ZonedDateTime to String
Python filter()
Python Tuple count()
Python String translate()
Python String find()
Python Program to Trim Whitespace From a String
Python Program to Convert Decimal to Binary Using Recursion
Python memoryview()