Reputation: 156
I have a simple replace() using a dict. This code is fully functional, but as soon as I change to a new variable name for the cleaned string, it stops working (step 2). My question is why I cannot create a new string (s2) in the second step?
words = {
"badword": "niceword",
"worseword": "nicerword"
}
#step1
sentence = input(">")
for key, value in words.items():
sentence = sentence.replace(key, value)
print(sentence)
#step2
sentence2 = input("s2>")
for key, value in words.items():
s2 = sentence2.replace(key, value) #here
print(s2)
Upvotes: 0
Views: 34
Reputation: 412
There is a problem with your logic.
You are doing it in two different ways
sentence = input(">")
for key, value in words.items():
sentence = sentence.replace(key, value)
You replace something in sentence for each item in your dict
As in this block you are doing it the wrong way
sentence2 = input("s2>")
for key, value in words.items():
s2 = sentence2.replace(key, value) #here
print(s2)
sentence2
is not the string that will be modified, you just save in s2 the result of sentence2.replace()
So you overwrite s2 each time with the original inputstring.
Upvotes: 1
Reputation: 52792
To keep the original string as well you'll have to copy the string before doing replacements, and then do the replacements on the copy.
s2 = sentence2 = input("s2>")
for key, value in words.items():
s2 = s2.replace(key, value) #here
print(sentence2, s2)
Otherwise you're overwriting s2
in each iteration, using the unaltered sentence2
as your source - in effect only having the last iteration of the loop matter (which replaces worseword
with nicerword
.
With your original code each step of the loop looks like this, with "badword worseword" as input:
s2 = "badword worseword".replace('badword', 'niceword')
# s2 is now niceword worseword
# but since you're still using sentence2, which is "badword worseword", the second
# iteration will still use the original string and not the changed one:
s2 = "badword worseword".replace('worseword', 'niceword')
.. and now s2 is badword niceword - since you're not using s2
but sentence2
as the string you're replacing content in in your loop.
Upvotes: 1