为什么我可以更新 python 中的列表切片但不能更新字符串切片?
只是好奇为什么 python 允许我更新列表的一部分而不是字符串?
>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
这有充分的理由吗? (我确信有。)
Just curious more than anything why python will allow me to update a slice of a list but not a string?
>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
Is there a good reason for this? (I am sure there is.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为在Python中,字符串是不可变的。
Because in python, strings are immutable.
Python 区分可变数据类型和不可变数据类型。使字符串不可变是 Python 中的一般设计决策。整数是不可变的,您无法更改
42
的值。在 Python 中,字符串也被视为值,因此您无法将“fourty-two”更改为其他内容。这一设计决策允许进行多项优化。例如,如果字符串操作不会更改字符串的值,CPython 通常只是返回原始字符串。如果字符串是可变的,则始终需要制作副本。
Python distinguishes mutable and immutable data types. Making strings immutable is a general design decision in Python. Integers are immutable, you can't change the value of
42
. Strings are also considered values in Python, so you can't change"fourty-two"
to something else.This design decision allows for several optimisations. For example, if a string operation does not change the value of a string, CPython usually simply returns the original string. If strings were mutable, it would always be necessary to make a copy.