首先,我是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'
它用string替换1
字符串2
。
在Python中,字符串是不可变的。因此,这:
>>> a[-1] = str(int(a[-1]) + 1)
不起作用:
TypeError: 'str' object does not support item assignment
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句