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 globals()
Python Shallow Copy and Deep Copy
Python String islower()
Python String startswith()
Converting String to Stream of chars
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Generators
Python str()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python frozenset()
Python pass statement
Python min()
Python Dictionary copy()
Python Dictionary clear()
Python Tuple count()
Python getattr()
Python Anonymous / Lambda Function
Python Program to Remove Punctuations From a String
Python divmod()
Java String Conversions
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Dictionary popitem()
Python Modules
Reading an HTTP Response Body as a String in Java
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Convert Celsius To Fahrenheit
Array to String Conversions
Python delattr()
Python Tuple
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python time Module
Python Program to Append to a File