Python Forum

Full Version: Problem with replace
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I am working on a filter and I want to replace some words with nothing and I found the methode with .replace("word", ""). I have tried it, I don't get an error but nothing changes when I print the variable.

Here is my code:

words = input()
test = words
	   test.replace("show", "")
	   test.replace("images", "")
	   test.replace("pictures", "")
	   test.replace("photos", "")
	   print("I will search for images of: " + test)
It does work.
>>> "green eggs and spam".replace("e", "")
'grn ggs and spam'
But it DOES NOT work in-place. You have to actually assign it's result to something. So...
test = words
test = test.replace("show", "")
test = test.replace("images", "")
print(test)
You need to assign it back to the variable

words = input()
test = words
test = test.replace("show", "")
test = test.replace("images", "")
test = test.replace("pictures", "")
test = test.replace("photos", "")
print("I will search for images of: " + test)
As nilamo beat me to it, I'll make the additional suggestion that you create a list of words you are trying to replace and loop through them:

words_to_replace = ["show", "images", "pictures", "photos"]
for word in words_to_replace:
    test = test.replace(word, "")
I thought about using for to but the problem with that is it gives results like this:

I will search for images of: pictures of hello
I will search for images of: pictures of hello
I will search for images of: of hello
Print it after the loop, not inside the loop. That way it's only printed once.