![](/img/trans.png)
[英]Setting a variable in a class and updating it with a method in python to re-use in the class
[英]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.