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!
Create a slice that starts at the end of the string, and moves backwards. In this particular example, the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1 , negative one, which means one step backwards.
Using a[::-1] in Python to Reverse an Object Like an Array or String. As we saw above, we have a[start: stop: step] step in slicing, and -1 means the last element of the array. Therefore, a[::-1] starts from the end till the beginning reversing the given sequence that was stored.
The reversed() Built-in Function join() to create reversed strings. However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.
Simply exclude the end range index...
>>> foo[3::-1] '3210'
Ironically, about the only option I think you didn't try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With