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 Machine Learning - Sebastian Raschka
Python Data Types
Python Program to Swap Two Variables
Python String replace()
Python String isdecimal()
Python Dictionary pop()
Python Closures
Python complex()
Python issubclass()
Python for Loop
Python Function Arguments
Reading an HTTP Response Body as a String in Java
Converting a List to String in Java
Python Program to Capitalize the First Character of a String
Python String isnumeric()
Encode a String to UTF-8 in Java
JavaScript Eval: run a code string
Python sorted()
Python hex()
Python Modules
Python Program to Check if a Number is Positive, Negative or 0
Check if a String is a Palindrome in Java
Python Operators
Python Program to Print all Prime Numbers in an Interval
Format ZonedDateTime to String
Python Program to Differentiate Between type() and isinstance()
Python List clear()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python List append()
Python strftime()
Python Program to Check Leap Year
Python zip()