String Slicing

Get familiar with string slicing in Python, including basic slicing, slicing with a step, reverse slicing, partial slicing, and slicing by character.

The technique of extracting a portion of a string by utilizing its indices is called slicing. Several real-world applications use slicing. For example, slicing can be used to extract the required information from messages sent over a communication because they conform to a specific format. Several data processing and cleaning tasks like web scraping, tokenization, and feature extraction also benefit from slicing.

Slicing in Python

For a given string, we can use the following template to slice it and retrieve a substring:

string[start:end]
  • The start index indicates where we want the substring to begin.

  • The end index specifies where we want the substring to terminate. The character at the end index will not be included in the substring obtained through this method.

Here’s an example illustrating the use of the slicing:

Python 3.10.4
my_string = "This is MY string!"
print(my_string[0:4])
print(my_string[1:7])
print(my_string[8:len(my_string)])

Explanation

Here’s the code explanation:

  • Line 2: This expression extracts a substring from my_string starting from the index 0 (inclusive) up to, but not including, the index 4. So it prints This, which are the characters at indices 0, 1, 2, and 3.

  • Line 3: This expression extracts a substring from my_string starting from the index 1 (inclusive) up to, but not including, the index 7. So it prints his is, which are the characters at indices 1, 2, 3, 4, 5, and 6.

  • Line 4: This expression extracts a substring from my_string starting from the index 8 (inclusive) until the end of the string. The len(my_string) function returns the length of the string, ensuring that it captures all characters until the end. So it prints MY string!, ...