[Python] Python reverse-stride slicing

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

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


    >>> foo = '0123456'
    >>> foo[0:4]
    '0123'
    >>> foo[::-1]
    '6543210'
    >>> foo[4:0:-1] # I was shooting for '3210' but made a fencepost error, that's fine, but...
    '4321'
    >>> foo[3:-1:-1] # How can I get '3210'?
    ''
    >>> foo[3:0:-1]
    '321'


    It seems strange that I can write foo[4:0:-1], foo[5:1:-1], etc. and get what I would expect, but there's no way to write the slice so that I get '3210'.

    A makeshift way of doing this would be foo[0:4][::-1], but this creates two string objects in the process. I will be performing this operation literally billions of times, so every string operation is expensive.

    I must be missing something silly and easy. Thanks for your help!

    Continue reading...

Compartilhe esta Página