为什么不调用字符串方法(如。修改(变异)字符串?为什么它不改变,除非我分配结果?

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

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

我想把单词 hello改为 goodbye,因此它应该把字符串 "hello world"改为 "goodbye world"。但是 X 仍然是 "hello world"。为什么我的代码不工作?

104378 次浏览

这是因为 字符串在 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()

诸如此类。

所有字符串函数(如 lowerupperstrip)都返回一个字符串,而不修改原来的。如果您试图修改字符串,正如您可能认为的 well it is an iterable,它将失败。

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

关于字符串不可变的重要性有一个很好的解读: 为什么 Python 字符串是不可变的? 使用它们的最佳实践是什么

字符串方法示例

给定一个文件名列表,我们希望将所有扩展名为 hpp 的文件重命名为扩展名为 h。

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
if i.endswith(".hpp"):
x = i.replace("hpp", "h")
newfilenames.append(x)
else:
newfilenames.append(i)




print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]