pythonstringslice

Why is slicing a string not working if step is not mentioned?


I am studying slicing in strings using the slicing operator :.

The string I have chosen is word = 'fabricated'.

According to me, the output for the below statements:

print(word[5:-8])
print(word[-3:-9])

should be:

cir
tacirb

However, nothing is getting printed on running these statements. Neither on Google Colab nor on VS Code.

But when I specifically mention the step parameter as follows:

print(word[5:-8:-1])
print(word[-3:-9:-1])

I get my expected output as:

cir
tacirb

I would like to understand why I am getting a string of length 0 although the step parameter is not mandatory.


Solution

  • As you note, the step size is not mandatory, but it defaults to None. In particular, word[5:-8] is equivalent to word[slice(5, -8)] or word[slice(5, -8, None)].

    When word.__getitem__ gets such a slice, it treats None the same as 1. (I suspect most __getitem__ implementations would, but they don't need to.) When the step size is positive, you only get a non-empty string if start < stop, regardless of the signs involved. When the step size is negative (i.e., when a negative step is explicitly provided), then a non-empty string is produced if stop < start (again, independent of the signs involved).