Python字符串替换不起作用 [英] Python String replace doesn't work

查看:60
本文介绍了Python字符串替换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to do a replace for something in a string. Here is the code I am testing:

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

我希望第二个输出会说hello all",但它两次都说hello world".没有错误,代码运行良好,只是什么都不做.我该如何解决这个问题?

I would expect the second output to say 'hello all' but it says 'hello world' both times. There are no errors, the code runs fine, it just doesn't do anything. How do I fix this?

推荐答案

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

Strings are immutable. That means that they cannot be changed. stringT.replace(...) does not change stringT itself; it returns a new string. Change that line to:

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

这篇关于Python字符串替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆