Python Program to find All Occurrence of a Character in a String

Write a Python Program to find All Occurrence of a Character in a String with a practical example.

Python Program to find All Occurrence of a Character in a String Example 1

This python program allows the user to enter a string and a character. Here, we used For Loop to iterate each character in a String. Inside the Python For Loop, we used the If statement to check whether any character in str1 String is equal to character ch or not. If true, then i value printed as output. Remember, i is an index position (starts with 0).

# Python Program to find Occurrence of a Character in a String

str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")

for i in range(len(str1)):
    if(str1[i] == ch ):
        print(ch, " is Found at Position " , i + 1)

Python all characters occurrence in a string output

Please enter your own String : tutorial gateway
Please enter your own Character : t
t  is Found at Position  1
t  is Found at Position  3
t  is Found at Position  12

Python Program to return All Occurrence of a Character in a String Example 2

This Python display all Occurrence of a Character in a String program is the same as the above. However, we just replaced the For Loop with While Loop.

# Python Program to find Occurrence of a Character in a String

str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
i = 0

while(i < len(str1)):
    if(str1[i] == ch ):
        print(ch, " is Found at Position " , i + 1)
    i = i + 1

Python all characters occurrence in a string output

Please enter your own String : hello world
Please enter your own Character : l
l  is Found at Position  3
l  is Found at Position  4
l  is Found at Position  10

Python Program to display Total Occurrence of a Character in a String Example 3

This Python finds All Occurrence of a Character in a String is the same as the first example. But, in this python program, we used the Functions concept to separate the Python logic.

# Python Program to find Occurrence of a Character in a String

def all_Occurrence(ch, str1):
    for i in range(len(str1)):
        if(str1[i] == ch ):
            print(ch, " is Found at Position " , i + 1)

string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
all_Occurrence(char, string)
Python Program to find All Occurrence of a Character in a String 3