Interview Content
- C Programming Coding Questions
- C Pattern Programming Questions
- C Programming Interview Questions
- Java Programming Coding Questions
- Java Pattern Programming Questions
- Java Programming Interview Questions
- Python Programming Coding Questions
- Python Pattern Programming Questions
- Python Programming Interview Questions
- SQL Interview Questions
Python Program to count occurrence of characters in string
Ans:
In this tutorial we will learn how to write program in Python to count occurrence of character in a String.
Also Read this: C program to count the occurrence of a character in String.
How this Python program will behave?
This Python program will take a string and a character as an input. And it will count the occurrence of a given character. This program will also count spaces I we will give it.
For example:
If we have given a String as an input “Quescol is educational website” and also a character ‘s’.
Then after counting character ‘a’, program will return output 2.
Python Program to count the occurrence of given character in a string.
Using for Loop:
string = input("Please enter String : ")
char = input("Please enter a Character : ")
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
print("Total Number of occurence of ", char, "is :" , count)
Output:
Using while Loop:
string = input("Please enter String : ")
char = input("Please enter a Character : ")
index, count = 0, 0
while(index < len(string)):
if(string[index] == char):
count = count + 1
index = index + 1
print("Total Number of occurence of ", char, "is :" , count)
Output:
Using Method:
def countOccur(char, string):
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
return count
string = input("Please enter String : ")
char = input("Please enter a Character : ")
count = countOccur(char, string)
print("Total Number of occurence of ", char, "is :" , count)
Output:
Also prepare these Python Programs:
- Write a program to reverse an integer in Python.
- Write a program in Python to check whether an integer is Armstrong number or not.
- Python Program to check a given number is Prime number or not.
- Write a program in Python to print the Fibonacci series using iterative method.
- Write a program in Python to print the Fibonacci series using recursive method.
Latest Uploads on Website
- AVL Tree with explanation
- Radix sort algorithm explanation with example
- Quick Sort Algorithm with explanation
- Bubble sorting algorithm with Bubble sort program in C
- Insertion sort algorithm and program in C
- Selection Sort Algorithm and Program in C
- Linear probing technique explanation with example
- Collision in Hashing and Collision resolution technique
- Hashing in data structure with its types
- Binary search tree operations with Program
- Binary search tree in data structure
- Binary search algorithm in data structure with explanation
- linear search in data structure with Algo and Program