为什么不调用字符串方法(例如 .replace 或 .strip)修改(变异)字符串?

问题描述 投票:0回答:3

我试过这段代码来做简单的字符串替换:

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

为什么

X
没有改变,从
"hello world"
"goodbye world"

python string
3个回答
251
投票

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

这意味着

X.replace("hello","goodbye")
返回
X
的副本并进行了替换
。因此,您需要更换这一行:

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

这条线:

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

更广泛地说,对于所有“就地”更改字符串内容的 Python 字符串方法都是如此,例如

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

等等。


0
投票

lower
upper
strip
这样的所有字符串函数都返回一个字符串而不修改原始字符串。如果你试图修改一个字符串,正如你可能认为的
well it is an iterable
,它会失败。

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

关于字符串不可变的重要性,有一篇很好的读物:Why are Python strings immutable?使用它们的最佳实践


-2
投票

字符串方法示例

给定文件名列表,我们要将所有扩展名为 hpp 的文件重命名为扩展名为 h。为此,我们想生成一个名为 newfilenames 的新列表,其中包含新文件名。

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"]
© www.soinside.com 2019 - 2024. All rights reserved.