CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
2
You visited us 2 times! Enjoying our articles? Unlock Full Access!
Question

Write a function deleteChar() which takes two parameters one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.

Open in App
Solution

Program 1:
#deleteChar function to delete all occurrences of char from string using replace() function
def deleteChar(string,char):
#each char is replaced by empty character
newString = string.replace(char,'')
return newString

userInput = input("Enter any string: ")
delete = input("Input the character to delete from the string: ")

newStr = deleteChar(userInput,delete)

print("The new string after deleting all occurrences of",delete,"is: ",newStr)


OUTPUT:
Enter any string: Good Morning!
Input the character to delete from the string: o
The new string after deleting all occurrences of o is: Gd Mrning!



Program 2:
#deleteChar function to delete all occurrences of char from string without using replace() function
def deleteChar(string,char):
newString = ''
#Looping through each character of string
for a in string:
#if character matches, replace it by empty string
if a == char:
#continue
newString += ''
else:
newString += a
return newString

userInput = input("Enter any string: ")
delete = input("Input the character to delete from the string: ")

newStr = deleteChar(userInput,delete)

print("The new string after deleting all occurrences of",delete,"is: ",newStr)


OUTPUT:
Enter any string: Good Evening!
Input the character to delete from the string: o
The new string after deleting all occurrences of o is: Gd Evening!

ā€‹ā€‹

flag
Suggest Corrections
thumbs-up
2
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Buzzy Bees
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon