I am using CodeHS for my Computer Science Principles class and one of the problems in the Strings section is really confusing me. We have to remove all of one string from another string.
These are the official instructions:
Write a function called remove_all_from_string that takes two strings, and returns a copy of the first string with all instances of the second string removed. You can assume that the second string is only one letter, like "a".
We are required use:
- A function definition with parameters
- A while loop
- The find method
- Slicing and the + operator
- A return statement
We are expected to only have to use those 5 things to make it work. I attempted to write this program but my function doesn't do anything and I am really stumped.
def remove_all_from_string(word, letter): while letter in word: x=word.find(letter) if x==-1: continue else: return x print word[:x] + word[x+1:] remove_all_from_string("alabama", "a") 25 Answers
def remove_all_from_string(word, letter): while letter in word: x=word.find(letter) if x == -1: continue else: word = word[:x] + word[x+1:] return word print(remove_all_from_string("hello", "l")) 1The easiest way to do this would obviously just be
def remove_all_from_string(word, letter): return word.replace(letter, "") However, considering the parameters, another way we could do this is like so:
def remove_all_from_string(word, letter): while letter in word: x=word.find(letter) if x == -1: continue else: word = word[:x] + word[x+1:] return word You could run this and print it by typing
>>> print(remove_all_from_string("Word Here", "e")) #returns Word hr def remove_all_from_string(word, letter): letters = len(word) while letters >= 0: x=word.find(letter) if x == -1: letters = letters - 1 continue else: # Found a match word = word[:x] + word[x+1:] letters = letters - 1 return word remove_all_from_string("alabama", "a") 0def remove_all_from_string(word, letter): while letter in word: num = word.find(letter) word = word[:num] + word[num+1:] return word 1I have this so far and it keeps saying that message is not defined and when I define it with find_secret_word it says "find_secret_word" is not defined, what do I do? This is my code:
word = "bananas" letter = "na" index = word.find(letter) def remove_all_from_string(word, letter): while letter in word: x=word.find(letter) if x == -1: continue else: word = word[:x] + word[x+1:] return word word = word[:index] + word[index+len(letter):] print(remove_all_from_string("hello", "l")) def find_secret_word(message): while True: return hidden_word hidden_word = "iCjnyAyT" for letter in message: if letter.upper(): hidden_word = hidden_word + letter print (find_secret_word(message)) 1