Python - Extended String slicing: The third limit and slice objects

Introduction

Python slice expressions have support for an optional third index.

It is used as a step.

The step is added to the index of each item extracted.

The full form of a slice is X[I:J:K].

It means "extract all the items in X, from offset I through J-1, by K.

K defaults to 1.

If you specify an explicit value, however, you can use the third limit to skip items or to reverse their order.

X[1:10:2] will fetch every other item in X from offsets 1-9.

It will collect the items at offsets 1, 3, 5, 7, and 9.

The first and second limits default to 0 and the length of the sequence, respectively.

X[::2] gets every other item from the beginning to the end of the sequence:

Demo

S = 'abcdefghijklmnop' 
print( S[1:10:2] )                          # Skipping items 
print( S[::2] )

Result

You can use a negative stride to collect items in the opposite order.

For example, "hello"[::-1] returns the new string "olleh".

The first two bounds default to 0 and the length of the sequence.

A step of -1 indicates that the slice should go from right to left.

The effect is to reverse the sequence:

Demo

S = 'hello' 
print( S[::-1] )                            # Reversing items

Result

With a negative stride, the meanings of the first two bounds are essentially reversed.

That is, the slice S[5:1:-1] fetches the items from 2 to 5, in reverse order.

The result contains items from offsets 5, 4, 3, and 2:

Demo

S = 'abcedfg' 
print( S[5:1:-1] )                          # Bounds roles differ 
# from w  w w  .  j a v a2 s  . co m
print( 'test'[1:3] )                        # Slicing syntax 
print( 'test'[slice(1, 3)] )                # Slice objects with index syntax + object 
print( 'test'[::-1] )
print( 'test'[slice(None, None, -1)] )

Result

Related Topic