gpt4 book ai didi

python - Python 中的 replace() 方法有什么特别之处?

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:05 25 4
gpt4 key购买 nike

首先,我是 Python 的初学者。因此,如果我的问题对您来说似乎很荒谬,我很抱歉。如果你有一个字符串值,例如:

a = 'Hello 11'

如果你输入:

a[-1] = str(int(a[-1]) + 1)

结果将是:'2'

但是如果你输入:

a.replace(a[-1], str(int(a[-1]) + 1))

结果将是:

'Hello 22' 而不是 'Hello 12'

为什么会这样?

最佳答案

看一下零件:

>>> a[-1]
'1'
>>> str(int(a[-1]) + 1)
'2'

这意味着:

>>> a.replace(a[-1], str(int(a[-1]) + 1))

这样做:

>>> a.replace('1', '2')
'Hello 22'

它将字符串 1 替换为字符串 2

在 Python 中,字符串是不可变的。因此,这:

>>> a[-1] = str(int(a[-1]) + 1)

不起作用:

TypeError: 'str' object does not support item assignment

关于python - Python 中的 replace() 方法有什么特别之处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com