Write a Python program to Remove the first Occurrence of a Character in a String using For Loop, while loop, and functions with an example.
Python Program to Remove the First Occurrence of a Character in a String Example
This python program allows the user to enter a string and a character. Next, it finds and removes the first occurrence of that character inside a given string using For Loop.
First, we used For Loop to iterate each character in a String. Inside the For Loop, we are using If Statement to check the character is equal to ch or not. If true, it uses the string slice index to remove that character and Break statement to exit the loop. Please refer String article to understand everything about Python Strings
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
string2 = ''
length = len(string)
for i in range(length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
print("Original String : ", string)
print("Final String : ", string2)
Python Program to Delete the First Occurrence of a Character in a String Example 2
This code to remove the first occurrence of a character is the same as above. However, we just replaced the For Loop with While Loop.
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
string2 = ''
length = len(string)
i = 0
while(i < length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
i = i + 1
print("Original String : ", string)
print("Final String : ", string2)
Remove the first character occurrence in a string output
Please enter your own String : python programs
Please enter your own Character : p
Original String : python programs
Final String : ython programs
Python Program to Delete First Occurrence of a String Character Example 3
This code to delete the first occurrence of a string is the same as the first example. But, this time, we used Python Functions to separate the logic.
def removeFirstOccur(string, char):
string2 = ''
length = len(string)
for i in range(length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
return string2
str1 = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
print("Original String : ", str1)
print("Final String : ", removeFirstOccur(str1, char))
Remove the first character occurrence in a string output
Please enter your own String : tutorialgateway
Please enter your own Character : t
Original String : tutorialgateway
Final String : utorialgateway