Python reverse-stride slicing

前端 未结 8 624
后悔当初
后悔当初 2020-12-02 20:22

A specific example of my question is, \"How can I get \'3210\' in this example?\"


>>> foo = \'0123456\'
>>> foo[0:4]
\'0123\'
>>> foo[::-1]
\'6543210\'
>>>          


        
8条回答
  •  情歌与酒
    2020-12-02 21:14

    Omit the end index in your slice notation:

    >>> foo = '0123456'
    >>> foo[3::-1]
    '3210'
    

    If you have to do this many times, create a slice object that you can use over and over

    >>> i = slice(3,None,-1)
    >>> foo[i]
    '3210'
    

提交回复
热议问题