Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reverse-stride slicing

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!

like image 848
eblume Avatar asked Apr 27 '11 00:04

eblume


People also ask

How do you slice backwards in Python?

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.

How do you reverse the order of sequence for slicing?

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.

How do you reverse a string backwards in Python?

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.


1 Answers

Simply exclude the end range index...

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

Ironically, about the only option I think you didn't try.

like image 99
Andrew White Avatar answered Sep 22 '22 15:09

Andrew White