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 String encode()
Python String rstrip()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Check Prime Number
Python Program to Print Hello world!
Python String swapcase()
Python Set update()
Python String isdecimal()
Python Program to Represent enum
Python Dictionary items()
Python chr()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Java – String to Reader
Python Program to Copy a File
Python Dictionary values()
Python Program to Get the Class Name of an Instance
Python String isalnum()
Most commonly used String methods in Java
Python print()
Python String translate()
APIs in Node.js vs Python - A Comparison
Python Program to Find Numbers Divisible by Another Number
Python str()
Python pass statement
Python ord()
String Initialization in Java
Python Program to Find the Largest Among Three Numbers
Python Get Current time
Python Shallow Copy and Deep Copy
Java String to InputStream
Python repr()