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 Set intersection_update()
Machine Learning with Python for everyone - Mark E.Fenner
Converting a Stack Trace to a String in Java
Python delattr()
Python String startswith()
Java String to InputStream
Python len()
Python Set union()
Python Package
Python String swapcase()
Python Program to Find the Size (Resolution) of a Image
Python Program to Randomly Select an Element From the List
Python Program to Find the Square Root
Python Dictionary setdefault()
Python String expandtabs()
Python Program to Count the Number of Each Vowel
Python Program to Get Line Count of a File
Python round()
CharSequence vs. String in Java
Deep Learning with Python - Francois Cholletf
Python List copy()
Python List
Generate a String
Python Program to Create a Long Multiline String
Python slice()
Python String rpartition()
Python Type Conversion and Type Casting
Python String isnumeric()
Python Program to Calculate the Area of a Triangle
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Intelligent Projects Using Python - Santanu Pattanayak
Python String center()