I want to know if when I do something like
a = "This could be a very large string..." b = a[:10]
a new string is created or a view/iterator is returned
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.
Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.
The slice operator [n:m] returns the part of the string starting with the character at index n and go up to but not including the character at index m.
Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.
Python does slice-by-copy, meaning every time you slice (except for very trivial slices, such as a[:]
), it copies all of the data into a new string object.
According to one of the developers, this choice was made because
The [slice-by-reference] approach is more complicated, harder to implement and may lead to unexpected behavior.
For example:
a = "a long string with 500,000 chars ..." b = a[0] del aWith the slice-as-copy design the string
a
is immediately freed. The slice-as-reference design would keep the 500kB string in memory although you are only interested in the first character.
Apparently, if you absolutely need a view into a string, you can use a memoryview
object.
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