繁体   English   中英

replace() 中的变量重用

[英]Variable re-use in replace()

我有一个使用字典的简单替换()。 此代码功能齐全,但一旦我更改为已清理字符串的新变量名,它就会停止工作(步骤 2)。 我的问题是为什么我不能在第二步中创建一个新字符串(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)

要保留原始字符串,您必须在替换之前复制字符串,然后在副本上进行替换。

s2 = sentence2 = input("s2>")

for key, value in words.items():
    s2 = s2.replace(key, value) #here

print(sentence2, s2)

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

使用您的原始代码,循环的每个步骤看起来像这样,输入为“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')

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

你的逻辑有问题。

您正在以两种不同的方式进行操作

sentence = input(">")
for key, value in words.items():
    sentence = sentence.replace(key, value)

您为字典中的每个项目替换句子中的内容

就像在这个块中一样,你做错了

sentence2 = input("s2>")
for key, value in words.items():
    s2 = sentence2.replace(key, value) #here
print(s2)

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

暂无
暂无

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

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