String Slicing in Python

4.5/5 - (2 votes)

String slicing is a concept to carve out a substring from a given string. Use slicing notation s[start:stop:step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start=0, stop=len(string), step=1). For example, the expression s[2:4] from string 'hello' carves out the slice 'll' and the expression s[:3:2] carves out the slice 'hl'.

Let’s have a look at several examples next.

String Slicing Default Start and Stop

In the following code snippet, you create a string and slice over the string using only the default arguments—it creates a copy of the original string.

>>> string = 'hello world'
>>> string[:]
'hello world'

String Slicing: How to Skip First Character

The next string slicing operation creates a new string starting after the first character. It uses a default stop index, so it slices over the whole string—excluding only the first character.

>>> string[1:]
'ello world'

String Slicing: How to Skip Last Character

You can use negative indices as start or stop arguments of the string slicing operation. In this case, Python starts counting from the right. For instance, the negative index -1 points to the last character in the string, the index -2 points to the second last and so on.

If you want to skip the last character of a string, you simply use -1 as the stop index of the slice operation:

>>> string[:-1]
'hello worl'

String Slicing: How to Skip Every Other Character

You can skip every other character by using step size 2 with default start and stop indices:

>>> string[::2]

String Slicing: Set All Three Arguments

If you set all three arguments, you can control the start index, the stop index, and the step size. This allows for powerful creation of new strings:

>>> string[1:6:2]
'el '

The language feature slicing does not only apply to lists, but also to strings. As both lists and strings are sequencing types, slicing is only one among several similarities. For example, you can also iterate over the characters in a string using the for loop (e.g. for c in word).

Puzzle Python String Slicing

Here’s an example puzzle to test and improve your understanding of the string slicing concept.

word = "bender"

What is the output of this code snippet?

Only half of the Finxter users can solve this puzzle. The other half of the users have problems identifying the correct end index of the slice. Recap, the end index is not included into the slice. Here you can see the indices of the puzzle word.


Are you a master coder?

Click to test your Python String Slicing skills on the application.

Related Video

The Ultimate Guide to Slicing in Python