为什么除非您分配其输出,否则调用 Python 字符串方法不会执行任何操作? [英] Why doesn't calling a Python string method do anything unless you assign its output?
问题描述
我尝试做一个简单的字符串替换,但我不知道为什么它似乎不起作用:
I try to do a simple string replacement, but I don't know why it doesn't seem to work:
X = "hello world"
X.replace("hello", "goodbye")
我想把hello
这个词改成goodbye
,所以要把字符串"hello world"
改成"goodbye>世界"
.但 X 仍然是 "hello world"
.为什么我的代码不起作用?
I want to change the word hello
to goodbye
, thus it should change the string "hello world"
to "goodbye world"
. But X just remains "hello world"
. Why is my code not working?
推荐答案
这是因为字符串在 Python 中是不可变的.
这意味着 X.replace("hello","goodbye")
返回 X
的副本,并进行了替换.因此,您需要替换此行:
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
用这一行:
X = X.replace("hello", "goodbye")
更广泛地说,这适用于所有就地"更改字符串内容的 Python 字符串方法,例如replace
,strip
,translate
,lower
/upper
,join
,...
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
如果你想使用它,你必须将它们的输出分配给某些东西而不是扔掉它,例如
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
等等.
这篇关于为什么除非您分配其输出,否则调用 Python 字符串方法不会执行任何操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!