【问题标题】:Python String replace doesn't work [duplicate]Python字符串替换不起作用[重复]
【发布时间】:2016-02-26 15:40:42
【问题描述】:

我正在尝试替换字符串中的某些内容。这是我正在测试的代码:

stringT = "hello world"
print(stringT)
stringT.replace("world", "all")
print(stringT)

我希望第二个输出会说“hello all”,但它两次都说“hello world”。没有错误,代码运行良好,只是没有做任何事情。我该如何解决这个问题?

【问题讨论】:

  • str.replace() 不会就地更改您的字符串。替换后需要重新分配结果。

标签: python string


【解决方案1】:

字符串是不可变的。这意味着它们无法更改。 stringT.replace(...) 不会改变 stringT 本身;它返回一个新字符串。将该行更改为:

stringT = stringT.replace("world", "all")

【讨论】:

  • 谢谢!感谢快速响应:)
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2017-07-25
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 2011-11-04
  • 2014-06-23
相关资源
最近更新 更多