Python Forum

Full Version: string slicing default value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If a slice with positive step like
[::1]
then the default value of starting point and ending point is
[0:len(list):1]
but the default values for negative step like [::-1] is
[len(list)-1:None:-1]
Is that right ? Correct me if i'm wrong please, and are there some mechanisms explain why python can switch between default values like that ? Thank you guys so much
Simple answer about difference: 0 and -0 are equal. So counting from end can’t start with -0 and starts with -1. This makes all subsequent indexes different from zero-based indexing used in forward direction.

EDIT: there is subtle distinction between 0 and None:

>>> s = 'python'
>>> s[0:0]
''
>>> s[None:None]
'python'
>>> s[:]           # same as [None:None]
'python'
You can omit start and stop indices, Python interprets these omissions as None (or in spoken language: 'from start', 'till end').

Some rules of thumb:

sequence[start:stop:step]

- sequence is object to be sliced
- start, stop, step are indices
- start index is included in slice, end index is first not included
- start, stop and step are separated by :
- to define stop and/or step previous indices must be defined
- if value omitted Python interprets it as None ([2:] to end; [:2] from start) which is different from 0 (specific index)