Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with replace
#1
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)
Reply
#2
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)
Reply
#3
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)
Reply
#4
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, "")
Reply
#5
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
Reply
#6
Print it after the loop, not inside the loop. That way it's only printed once.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Beginner problem, replace function with for loop Motley_Cow 9 4,535 Sep-13-2019, 06:24 AM
Last Post: Motley_Cow
  problem in replace string into file Saeid_Bibak 1 2,047 Jan-20-2019, 09:46 PM
Last Post: Gribouillis
  Search & Replace - Newlines Added After Replace dj99 3 3,356 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020