Python String – Indexing and Slicing


String Indexing

As a string is a collection of characters stored as an ordered sequence, each character is assigned the index position starting with 0. We can access each character by passing the index position in the square brackets.

Example:

name = ‘Peter Cruise’

Index Positions:

0 1 2 3 4 5 6 7 8 9 10 11
P e t e r space C r u i s e
In [1]:
name = 'Peter Cruise'

Check what is at position 0.

In [2]:
print(name[0])
P

Position 4.

In [3]:
print(name[4])
r

String Slicing

The slicing operation can extract a substring of two or more than two characters. While performing slicing, we can pass three optional parameters in the square brackets separated by a colon.

String[StartPosition : EndPosition : Step]


Python String - Indexing and Slicing

When we do not use a colon, the argument is considered to be the individual character’s position.

Let us understand index positions with some examples:

Only using start to end.

In [1]:
name = 'Peter Cruise'
print(name[0:])
Peter Cruise

Start with 3 to end.

In [2]:
print(name[3:])
er Cruise

Go up to 3. Note: Character at position 3 will not be included.

In [3]:
print(name[:3])
Pet

Include all with jump of 2.

In [4]:
print(name[::2])
PtrCus

Start at 2 up to 8.

In [5]:
print(name[2:8])
ter Cr

Start with 1 up to 11 with jump of 3.

In [6]:
print(name[1:11:3])
errs

Negative Indexing

We can also use negative indexing. The last letter has the index position of -1. It keeps on increasing in the negative order until the first character. If we want to traverse backward, we can use step as a negative number. Example: -1.

Example:

name = ‘Peter Smith’

Negative Index Positions:

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
P e t e r space S m i t h

Character at -2 position.

In [1]:
name = 'Peter Smith'
print(name[-2])
t

This will not work because the default jump size is 1 which is positive but to traverse backward we need a negative jump size.

In [2]:
print(name[-2:-6])

Traversing from -2 uptill -6 with jump of -1.

In [3]:
print(name[-2:-6:-1])
timS

Traversing from -5 to -2 with a positive jump i.e. default 1.

In [4]:
print(name[-5:-2])
Smi

Reversing a String

We can reverse the string by using the negative indexing trick. We have to specify the step as -1.

In [1]:
name = 'Peter Smith'
print(name[::-1])
htimS reteP

Slice Method

The slice method in Python is a built-in function that returns a slice object, which can be used for slicing strings (and other iterable objects).

Syntax:

slice(start, stop, step)

You might have already observed that it has the same parameters as we used while String slicing, i.e start, stop, step.

Default values

The slice method allows you to omit parameters. If you omit the start, stop, or step parameter, it will be considered as None. By default, if you specify only a single argument, then it is considered as the stop argument. But if you want to specify start and skip stop, then you need to use None for stop. In the same way, if you would like to specify the stop, then it is better to use None for start for more clarity.

Example:

If we have only single element, by default, it is End argument.

In [1]:
name = "Logical Python"
name[slice(7)]
Out[1]:
'Logical'

Start as None, means it will start from 0.

In [2]:
name = "Logical Python"
name[slice(None,7)]
Out[2]:
'Logical'

Stop as None, means it will go till last chanracter.

In [3]:
name = "Logical Python"
name[slice(8, None)]
Out[3]:
'Python'

Both Start and Stop as None, with jump of 2.

In [4]:
name = "Logical Python"
name[slice(None, None,2)]
Out[4]:
'LgclPto'

Slice Object

A slice object, is used to encapsulate the start, stop and step parameters in a reusable and versatile form. The main advantage of the slice object is to re-use these parameters multiple times in the Program.

Syntax:

slice_obj = slice(start, stop, step)

Example:

In [1]:
obj = slice(None,7)
name = "Logical Python"
name[obj]
Out[1]:
'Logical'

Resources

Handwritten Notes

References:

  1. Slicing and Indexing in Python
  2. Slice Object
  3. Python – Slicing Strings Examples