|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在字符串中替换某个字符时,使用切片无法替换
>>> name = 'Henny'
>>> naume[0] = 'P'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
使用replace方法可以替换
>>> name = 'Henny'
>>> name.replace('H', 'P')
'Penny'
>>> name
'Henny'
replace替换后并不改变name的值,如何理解?
第一个问题:
字符串创建后是不可改变的,就像元祖一样。可改变的是'列表' 等等
第二个问题:
看官方的帮助文档
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
写的很清楚,是先对原始字符串进行复制,在对复制后的进行替换
|
|