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

Mah*_*eeb 3 python string python-3.x

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

a = 'Hello 11'
Run Code Online (Sandbox Code Playgroud)

如果你输入:

a[-1] = str(int(a[-1]) + 1)
Run Code Online (Sandbox Code Playgroud)

结果将是: '2'

但如果你输入:

a.replace(a[-1], str(int(a[-1]) + 1))
Run Code Online (Sandbox Code Playgroud)

结果将是:

' Hello 22'而不是'Hello 12'

为什么会这样?

Mik*_*ler 8

看看这些部分:

>>> a[-1]
'1'
>>> str(int(a[-1]) + 1)
'2'
Run Code Online (Sandbox Code Playgroud)

这意味着:

>>> a.replace(a[-1], str(int(a[-1]) + 1))
Run Code Online (Sandbox Code Playgroud)

做这个:

>>> a.replace('1', '2')
'Hello 22'
Run Code Online (Sandbox Code Playgroud)

它用字符串替换1字符串2.

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

>>> a[-1] = str(int(a[-1]) + 1)
Run Code Online (Sandbox Code Playgroud)

不起作用:

TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)