【问题标题】:Why replace method is adding more elements rather than replacing existing ones?为什么替换方法是添加更多元素而不是替换现有元素?
【发布时间】:2021-03-07 02:18:43
【问题描述】:

我正在尝试制作一个根据字典将字母更改为另一个字母的代码。例如,如果它在字符串中找到字母“o”,则会更改为“e”。我想出的方法在技术上可行,但由于某种原因仍然添加了更多元素,不幸的是我无法弄清楚。 (Python初学者) 代码如下:

dict1 = {"o":"e", "p":"l"}
text = "op"
text2 = ""
for key,value in dict1.items():
    y = text.replace(key,value)
    text2 +=y
print(text2)

【问题讨论】:

标签: python


【解决方案1】:

您正在执行按键更新并将它们附加到一个空字符串。只需使用

dict1 = {"o":"e", "p":"l"}
text = "op"
for key,value in dict1.items():
    text = text.replace(key,value)
print(text)

ytext2 的值:

  1. y='ep' -> text2 = '' + 'ep' = 'ep'
  2. y='ol' -> text2 = 'ep' + 'ol' = 'epol'

【讨论】:

  • 不过,这在更一般的情况下不起作用,在这种情况下,一些替换可能会在以后再次被替换。
  • @ThierryLathuille 这是对 OP 代码的最小更新。如果他们想修复他们的算法逻辑,我会迭代文本字符,而不是一次更新整个文本的字符,但是嘿。
猜你喜欢
  • 1970-01-01
  • 2021-11-02
  • 2011-10-19
  • 2014-04-15
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
相关资源
最近更新 更多