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:
Java InputStream to String
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Get the File Name From the File Path
Map to String Conversion in Java
Python hash()
Python Set symmetric_difference_update()
Python String capitalize()
Debug a JavaMail Program
Converting a Stack Trace to a String in Java
Python hasattr()
Python Numbers, Type Conversion and Mathematics
Python Operator Overloading
Python globals()
Python String center()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Convert Celsius To Fahrenheit
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python del Statement
Python Set difference()
Python Generators
Python Program to Find Sum of Natural Numbers Using Recursion
Python vars()
Python Program to Print Hello world!
Python ord()
String Initialization in Java
Python type()
Converting a List to String in Java
Python Dictionary clear()
Reading an HTTP Response Body as a String in Java
Check If a String Is Numeric in Java
Python String maketrans()
Python Program to Randomly Select an Element From the List