Akron Children's Logo
Skip to main content

def remove_all_from_string(word, letter): # If the letter to remove is empty, return the original word if letter == "": return word while True: # Find the first occurrence of the letter index = word.find(letter) # If .find() returns -1, the letter is no longer in the string if index == -1: return word # Rebuild the string by skipping the found instance word = word[:index] + word[index + len(letter):] # Example usage: # word = input("Enter word: ") # letter = input("Enter letter to remove: ") # print(remove_all_from_string(word, letter)) Use code with caution. Copied to clipboard Breakdown of the Code

You can solve this using a while loop to repeatedly find and remove the target substring until it no longer exists in the word.

While the CodeHS exercise often requires the manual loop approach above, the simplest way to do this in standard Python is using the .replace() method:

: This method returns the starting index of the first occurrence of letter . If it isn't found, it returns -1 .

7.6 / 10 123... Site

def remove_all_from_string(word, letter): # If the letter to remove is empty, return the original word if letter == "": return word while True: # Find the first occurrence of the letter index = word.find(letter) # If .find() returns -1, the letter is no longer in the string if index == -1: return word # Rebuild the string by skipping the found instance word = word[:index] + word[index + len(letter):] # Example usage: # word = input("Enter word: ") # letter = input("Enter letter to remove: ") # print(remove_all_from_string(word, letter)) Use code with caution. Copied to clipboard Breakdown of the Code

You can solve this using a while loop to repeatedly find and remove the target substring until it no longer exists in the word. 7.6 / 10 123...

While the CodeHS exercise often requires the manual loop approach above, the simplest way to do this in standard Python is using the .replace() method: def remove_all_from_string(word, letter): # If the letter to

: This method returns the starting index of the first occurrence of letter . If it isn't found, it returns -1 . If it isn't found, it returns -1

Back to top of page

By using this site, you consent to our use of cookies. To learn more, read our privacy policy.