Python - String Indexing and Slicing

Introduction

Strings are defined as ordered collections of characters.

We can access their characters by position.

In Python, characters in a string are fetched by indexing.

Python offsets start at 0 and end at one less than the length of the string.

Python can fetch items from sequences such as strings using negative offsets.

A negative offset is added to the length of a string to derive a positive offset.

You can think of negative offsets as counting backward from the end.

The following interaction demonstrates:

Demo

S = 'test' 
print( S[0], S[-2] )                         # Indexing from front or end 
print( S[1:3], S[1:], S[:-1] )               # Slicing: extract a section
# from w w w. j a v a2  s .  c o  m

Result

The first line defines a four-character string and assigns it the name S.

The next line indexes it in two ways:

  • S[0] fetches the item at offset 0 from the left-the one-character string 's';
  • S[-2] gets the item at offset 2 back from the end-or equivalently, at offset (4 + (-2)) from the front.

The leftmost item is at offset 0, but the rightmost is at offset -1.

Positive offsets start from the left end (offset 0 is the first item).

Negatives count back from the right end (offset -1 is the last item).

Either kind of offset can be used to give positions in indexing and slicing operations.

The last line in the preceding example demonstrates slicing.

S[1:3] extracts the items at offsets 1 and 2: it grabs the second and third items, and stops before the fourth item at offset 3.

S[1:] gets all items beyond the first:the upper bound, not specified, defaults to the length of the string.

S[:-1] fetches all but the last item: the lower bound defaults to 0, and -1 refers to the last item, noninclusive.

Related Topics