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 Input, Output and Import
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Exception Handling Using try, except and finally statement
Python frozenset()
Python List insert()
Python tuple()
Count Occurrences of a Char in a String
Python Program to Display Fibonacci Sequence Using Recursion
Python range()
Python List index()
JavaScript Character classes
Python String upper()
Python String splitlines()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Compute all the Permutation of the String
Python map()
Converting String to Stream of chars
Python property()
Python Program to Print all Prime Numbers in an Interval
Python staticmethod()
String Hashing
Python sum()
Deep Learning with Python - Francois Chollet
Python Program to Print the Fibonacci sequence
Python Keywords and Identifiers
Python Set remove()
Python next()
Format ZonedDateTime to String
Python Program to Append to a File
Python Numbers, Type Conversion and Mathematics
Python Tuple index()
Python Program to Convert Kilometers to Miles