What are the default slice indices in Python *really*?

后端 未结 6 1711
死守一世寂寞
死守一世寂寞 2020-11-30 11:53

From the python documentation docs.python.org/tutorial/introduction.html#strings:

Slice indices have useful defaults; an omitted first index defaults

6条回答
  •  無奈伤痛
    2020-11-30 12:28

    The end value is always exclusive, thus the 0 end value means include index 1 but not 0. Use None instead (since negative numbers have a different meaning):

    >>> s[len(s)-1:None:-1]
    'gnirtsym'
    

    Note the start value as well; the last character index is at len(s) - 1; you may as well spell that as -1 (as negative numbers are interpreted relative to the length):

    >>> s[-1:None:-1]
    'gnirtsym'
    

提交回复
热议问题