[Tutor] slicing a string
steve at pearwood.info
Tue Sep 7 00:47:16 CEST 2010
On Tue, 7 Sep 2010 08:14:59 am lists wrote:
> Hi guys,
> Continuing my Python learning, I came across an exercise which asks
> me to take a string and reverse it.
> I understand that there is a function to do this i.e mytext.reverse()
You understand wrong :)
There is a function reversed() which takes any iterable object (a list,
a string, a tuple, a set, ...) and returns an iterator that yields the
items in reverse order:
<reversed object at 0xb7e8834c>
but that's not useful in this case.
> I imagine that the exercise author would rather I did this the hard
> way however. ;-)
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
Remember that slice indexes fall *between* characters:
A slice of [-1:-4:-1] is equivalent to [3:0:-1].
So, what does this slice do? The slice indexes are equivalent to:
range(3, 0, -1)
=> [3, 2, 1]
Remember that the end position is excluded! Hence you reverse all the
characters in the string *except* the first.
More information about the Tutor