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 string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.
When you slice strings, they return a new instance of String. Strings are immutable objects.
Slicing StringsSpecify the start index and the end index, separated by a colon, to return a part of the string.
Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.
Because in python, strings are immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With