The most common answer is:
update the function to return word with all instances of letter removed!
word = “Egg”
letter = “g”
def remove_all_from_string(word, letter):
while True:
index = word.find(letter)
if index == -1:
return word
word = word[:index] + word[index+1:]
return word
print (remove_all_from_string(word, letter))
This function remove_all_from_string is intended to remove all instances of letter from word. The loop and string slicing logic you’ve used are on the right track but can be simplified.
Additionally, the return word statement within the loop will never be reached because of the preceding return statement when index == -1. Let’s streamline the function and correct it:
word = "Egg"
letter = "g"
def remove_all_from_string(word, letter):
# A more straightforward way to remove all instances of letter from word
return word.replace(letter, "")
print(remove_all_from_string(word, letter))
This version uses the str.replace(old, new)
method to replace all instances of letter
with an empty string, effectively removing them. This approach is more concise and directly accomplishes the goal without manually searching for indices and slicing the string.
Leave a comment