In this Python Program, we will learn how to find the first occurrence of a character in a given string.
Here is the source code of the program to find the first occurrence of a character in a given string.
Python Program to find the First Occurrence of a Character in a given String Using For Loop
# Python Program to find First Occurrence of a Character in a given String Using For Loop
# Take the Input From the User
string = input("Enter The String: ")
char = input("Enter a Character to Check its First Occurrence: ")
# make string to lower to avoid case-sensitiveness of a character
string=string.lower()
flag = 0
for i in range(len(string)):
if(string[i] == char):
flag = 1
break
if(flag == 0):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", char, " is Found at Position " , i + 1)
Enter The String: Tutorials Rack is an Online Learning Website
Enter a Character to Check its First Occurrence: i
The first Occurrence of i is Found at Position 6
Python Program to find the First Occurrence of a Character in a given String Using While Loop
# Python Program to find First Occurrence of a Character in a given String Using While Loop
# Take the Input From the User
string = input("Enter The String: ")
char = input("Enter a Character to Check its First Occurrence: ")
# make string to lower to avoid case-sensitiveness of a character
string=string.lower()
i = 0
flag = 0
while(i < len(string)):
if(string[i] == char):
flag = 1
break
i = i + 1
if(flag == 0):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", char, " is Found at Position " , i + 1)
Enter The String: Tutorials Rack is an Online Learning Website
Enter a Character to Check its First Occurrence: a
The first Occurrence of a is Found at Position 7
Python Program to find the First Occurrence of a Character in a given String By Defining a function
# Python Program to find First Occurrence of a Character in a given String By Defining a function
def first_Occurrence_char(char, string):
# make string to lower to avoid case-sensitiveness of a character
string = string.lower()
for i in range(len(string)):
if(string[i] == char):
return i
return -1
# Take the Input From the User
string = input("Enter The String: ")
char = input("Enter a Character to Check its Last Occurrence: ")
flag = first_Occurrence_char(ch, str1)
if(flag == -1):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", ch, " is Found at Position " , flag + 1)
Enter The String: Tutorials Rack is an Online Learning Website
Enter a Character to Check its Last Occurrence: r
The first Occurrence of r is Found at Position 5
Comments