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.
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.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Below is the implementation of the deleteChar()
function:
def deleteChar(s, ch):
"""
Function to delete all occurrences of `ch` from the string `s`.
Parameters:
s (str): The input string.
ch (str): The character to be deleted.
Returns:
str: The string after deleting all occurrences of `ch`.
"""
new_str = ""
for character in s:
if character != ch:
new_str += character
return new_str
# Example usage
s = "Hello World!"
ch = 'o'
result = deleteChar(s, ch)
print("Original String:", s)
print("Modified String:", result)
Example output:
Original String: Hello World!
Modified String: Hell Wrld!
Explanation:
The function deleteChar() takes two parameters:
s
(the string) andch
(the character to remove).It iterates over each character in the string
s
.If the character is not equal to
ch
, it appends it tonew_str
.Finally, it returns the
new_str
, which is the modified string without occurrences ofch
.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month