1

I'm interested in how is Python handling slicing where the stop attribute is larger than the length of the string we are working with, for example:

my_string = 'abc'
my_slice = my_string[:10]

I am aware that my_slice == 'abc', what interests me is how efficient this is and how it works under the hood. I've read Time complexity of string slice and Understanding slice notation, but didn't find the exact case I was looking for.

My guess based on mentioned sources would be that a shallow copy of the string is returned (my_string[:10] is the same as my_string[:] in this case), is this the case?

robocat314
  • 141
  • 8
  • 1
    In the CPython interpreter small strings are cached so in this case `my_string[:10]` and `my_string[:]` would most likely return the exact same str object as `my_string` – Iain Shelvington Aug 18 '21 at 08:31
  • 1
    @IainShelvington - small strings that could be identifiers - so having spaces in your string (for example) means that they aren't cached. – Tony Suffolk 66 Aug 18 '21 at 09:08
  • @TonySuffolk66 thanks for the information. Interestingly making a "copy" of a string that contains spaces like this still returns the same object, I guess the implementation returns the same object in this case as an optimisation – Iain Shelvington Aug 18 '21 at 09:14

2 Answers2

0

The logic of python is that it will extract all the values that are before that index in the list.

So if the stop value is higher than the length of the list it will return the whole list because all the values' indexes are under the stop number, so it will extract all the values.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

Slicing in Python follows the following format:

myVar[fromIndex:toIndex]

The end of the slicing marked by the toIndex, counts to its index, which is one character less:

my_string = 'abc'
print(my_string[2]) #Output: 'c'
print(my_string[:2]) #Output: 'ab'

If we set a final index greater than the length of characters of the data, it will take it entire (it prints from the first value to the last one found). For example (following the example you have given):

0 1 2 3
a b c

my_string = 'abc'
print(my_string[:len(my_string)]) #Output: 'abc'

With the following example, you can clearly see that [:] (being the full length of the string) is equivalent to printing the value by slicing from the beginning to the end of the string:

0 1 2
a b c

my_string = 'abc'
print(my_string[:]) #Output: 'abc'

0 1 2 3
a b c

my_string = 'abc'
print(len(my_string)) #Output: '3'
print(my_string[:len(my_string)]) #Output: 'abc'