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 split()
Python String encode()
Python Program to Get a Substring of a String
Python @property decorator
Python hex()
Format ZonedDateTime to String
Python Program to Split a List Into Evenly Sized Chunks
Python String capitalize()
Python Set union()
Python Program to Convert Two Lists Into a Dictionary
Python Custom Exceptions
Python String lstrip()
Convert String to int or Integer in Java
Python Program to Catch Multiple Exceptions in One Line
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python all()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Access Index of a List Using for Loop
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
JavaScript Methods of RegExp and String
Introduction to Scientific Programming with Python - Joakim Sundnes
Split a String in Java
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Deep Learning with Python - Francois Cholletf
Python Anonymous / Lambda Function
Python String casefold()
Python Dictionary popitem()
Python Set update()
Python Dictionary copy()
Convert char to String in Java
Python Program to Check If a String Is a Number (Float)
Python Program to Find the Square Root