简体   繁体   English

replace() 中的变量重用

[英]Variable re-use in replace()

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).此代码功能齐全,但一旦我更改为已清理字符串的新变量名,它就会停止工作(步骤 2)。 My question is why I cannot create a new string (s2) in the second step?我的问题是为什么我不能在第二步中创建一个新字符串(s2)?

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)

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 .否则,您将在每次迭代中覆盖s2 ,使用未更改的sentence2作为源 - 实际上只有循环的最后一次迭代(它用worseword替换了nicerword

With your original code each step of the loop looks like this, with "badword worseword" as input:使用您的原始代码,循环的每个步骤看起来像这样,输入为“badword badword”:

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. .. 现在 s2 是 badword niceword - 因为您没有使用s2而是使用sentence2作为您在循环中替换内容的字符串。

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. sentence2不是要修改的字符串,您只需将sentence2.replace()的结果保存在 s2 中,因此您每次都用原始输入字符串覆盖 s2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM