除非分配输出,为什么调用Python字符串方法不做任何事情?

问题:除非分配输出,为什么调用Python字符串方法不做任何事情?

我尝试做一个简单的字符串替换,但是我不知道为什么它似乎不起作用:

X = "hello world"
X.replace("hello", "goodbye")

我想将单词更改hellogoodbye,因此应将字符串更改"hello world""goodbye world"。但是X仍然存在"hello world"。为什么我的代码不起作用?

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")

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?


回答 0

这是因为字符串在Python中是不可变的

这意味着将X.replace("hello","goodbye")返回的副本,X其中包含已替换的副本。因此,您需要替换此行:

X.replace("hello", "goodbye")

用这一行:

X = X.replace("hello", "goodbye")

更广泛地说,这是所有Python字符串的方法是“就地”修改字符串的内容真实,例如replacestriptranslatelower/ upperjoin,…

如果要使用它而不要将其丢弃,则必须将其输出分配给某些东西。

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

等等。

This is because strings are immutable in Python.

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")

with this line:

X = X.replace("hello", "goodbye")

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,…

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.


回答 1

所有的字符串功能lowerupperstrip而没有修改原始返回的字符串。如果您尝试修改一个字符串(可能会想到)well it is an iterable,它将失败。

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

关于字符串不可更改的重要性的文章很好读:为什么Python字符串不可更改?使用它们的最佳实践

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them