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.)
因为在python中,字符串是不可变的 。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.