;

Python Program to Find All the Occurrence of a Specific Character in a Given String


Tutorialsrack 28/04/2020 Python

In this Python Program, we will learn how to find all the occurrences of a specific character in a given string.

Here is the source code of the program to find all the occurrences of a specific character in a given string.

Program 1: Python Program to find All the Occurrence of a Character in a Given String Using For Loop

In this program, we use the for loop to iterate each character in a string and use the if statement inside the loop to match with the given character in a string.

Python Program to find All the Occurrence of a Character in a Given String Using For Loop

# Python Program to find All the Occurrence of a Character in a Given String Using For Loop

# Take The Input From the User
str1 = input("Enter the String: ")
ch = input("Enter The Character To Find All the Occurrence: ")
# make string to lower to avoid case-sensitiveness of a character
str1 = str1.lower()

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

Output

Enter the String: Python Program to find All the Occurrence of a Character in a Given String

Enter The Character To Find All the Occurrence: a

a  is Found at Position  13

a  is Found at Position  24

a  is Found at Position  46

a  is Found at Position  50

a  is Found at Position  52

a  is Found at Position  61

Program 2: Python Program to find All the Occurrence of a Character in a Given String Using While Loop

In this program, we use the While loop to iterate each character in a string and use the if statement inside the loop to match with the given character in a string.

Python Program to find All the Occurrence of a Character in a Given String Using While Loop
# Python Program to find All the Occurrence of a Character in a Given String Using While Loop

# Take The Input From the User
str1 = input("Enter the String: ")
ch = input("Enter The Character To Find All the Occurrence: ")

# make the string to lower to avoid case-sensitiveness of a character
str1 = str1.lower()

i = 0

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

Enter the String: Python Program to find All the Occurrence of a Character in a Given String

Enter The Character To Find All the Occurrence: i

i  is Found at Position  20

i  is Found at Position  58

i  is Found at Position  64

i  is Found at Position  72


Related Posts



Comments

Recent Posts
Tags