Problem with replace - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Problem with replace (/thread-7239.html) |
Problem with replace - hello_its_me - Dec-29-2017 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) RE: Problem with replace - nilamo - Dec-29-2017 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) RE: Problem with replace - newuserzing - Dec-29-2017 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) RE: Problem with replace - Mekire - Dec-29-2017 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, "") RE: Problem with replace - hello_its_me - Dec-29-2017 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 RE: Problem with replace - nilamo - Dec-29-2017 Print it after the loop, not inside the loop. That way it's only printed once. |