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.
python
Function to delete all occurrences of a character from a string
def deleteChar(string, char): # Create an empty string newstr = '' for character in string: # Check if character is not equal to the character to be deleted if character != char: newstr += character return newstr
End of function
Main program to test the function
st = input("Enter a string: ") ch = input("Enter the character to be deleted: ") result = deleteChar(st, ch) print("The original string is:", st) print("The modified string is:", result)
Output:
Enter a string: Hello World Enter the character to be deleted: l The original string is: Hello World The modified string is: Heo Word
The function deleteChar() takes two parameters: a string and a character. It creates an empty string named newstr to store the result. Using a for loop, it iterates through each character in the input string. Inside the loop, an if statement checks if the current character is not equal to the character to be deleted. If the condition is true, the character is concatenated to newstr using the += operator. Finally, the function returns the new string with all specified characters removed.
Explanation
This answer follows the pattern shown in Program 8-2 from the textbook, which demonstrates how to create a new string by iterating through characters and conditionally adding them. The function uses the same approach of creating an empty string, looping through each character, checking a condition, and building the result string. The logic is inverted from Program 8-2 - instead of replacing matching characters, we exclude them from the new string.
Solution Steps
Step 1: Define function deleteChar() with two parameters - string and char
Step 2: Create an empty string newstr to store the result
Step 3: Use a for loop to iterate through each character in the string
Step 4: Check if current character is NOT equal to the character to delete
Step 5: If condition is true, concatenate the character to newstr
Step 6: Return the new string after the loop completes