String Slicing in Python

Video Tutorial
FREE
String Slicing thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate
Topics Covered

Overview

Python has introduced multiple string operation methods that allow fetching a string substring. One of these operations is called Slice. This operator is so versatile and syntactically elegant that with the help of just a few parameters, one can fetch numerous substring combinations out of a string. String slicing in python programming is all about fetching a substring from a given string by slicing it from a ‘start’ index until a ‘stop’ index.

slice()

Python provides us with a method slice() that creates a ‘slice’ object that contains a set of ‘start’ & ‘stop’ indices and step values. To be specific about the parameters, it is (start, stop, step).

According to Python’s official documentation on string slicing in python: Slice has two different implementations,i.e.slice has two overload methods, each taking two different sets of parameters:

  • slice(stop) // takes start as 0 & step as 1

  • slice (start, stop, step)

    • start: is the starting index of the string on which the slicing operation has to be performed. It determines from where the slicing of the string will ‘begin’.
    • stop: is the stopping index of the slicing, ‘until’ which slicing operation has to be performed, i.e, the stop index is excluded while generating the substring.
    • step: It is an optional argument that defines the steps when iterating the list, i.e. it allows us to skip over elements.

Both slice() implementations return an object of the format slice(start, stop, end). (Check example-1)

This returned object can now be used to slice string, list, tuple, set, bytes, or range objects.

Application:

Example 1 – Fetching substring using slice object

Output

Explanation:

Slice() has two implementations, one with a single parameter and another with three parameters. Implementation with one parameter takes ‘stop’ index as the only and mandatory parameter whereas Implementation with three parameters takes ‘start’ index, ‘stop’ index, and OPTIONAL ‘step’ value as well.

In the above example ( check s1, s2 & s3 in the code snippet & output):

  • In s1: We first used slice() that takes only one ‘stop’ parameter. In the output, we received substring as “Welcom” as the ‘start’ index was automatically set to ‘0’ and ‘stop’ was set as 6.
  • In s2: After that, we used slice() with a three parameter-method but chose not to provide an optional ‘step’ parameter. In the output, we received a substring from index ‘2’ until ‘7’, as we provided ‘start’ as ‘2’ & ‘stop’ as ‘8’.
  • In s3: We implement slice() with ‘step’ as well. As we provided ‘step’ as 2. In the output, we received a substring by advancing to every 2nd element starting from index 1 to 20

Hence, now it’s clear that ‘step’ value determines with what value will your iterator (while forming the substring) advance or increment.

Note: understand that ‘stop’ index means it doesn’t stop ‘at’ this or ‘after’ this index. It stops right before this index when performing slicing. Whereas ‘start’ index is included in the string being sliced.

Indexing Syntax

Indexing syntax of a slice is a shorthand or a better substitute of slice() as it’s easier to understand and execute. It’s one of those operations and syntax that you appreciate as a developer and subconsciously lookout to apply in your code as it really is a cool operation!

Indexing Syntax:

String[start : stop : step]

So here, instead of creating a slice object first and then implementing it on the string, we directly use the indexing syntax that performs the same operation.

Replicating Example-1 with indexing syntax:

Example 2 – Indexing syntax for a slice

Output:

Note:

  • ‘Step’ can never be zero.
  • String[ : : ] => start = 0, stop = length of string, step = 1.
  • String[2 : : ] => start = 2, stop = length of string, step = 1
  • String[ :2: ] => start = 0, stop = 2, step = 1
  • String[:6] OR String[1:6] => are valid syntaxes as ‘step’ is an optional parameter for this operation.

Slice is an operation that takes just three parameters, and there is a lot more that can be done with it. Let’s take a look at some examples that will explain multiple use cases of this operator.

Using Negative index

‘Start’ and ‘stop’ indices and the step can have a negative value, respectively. But what impact do negative indices and negative ‘step’ really have on string slicing in Python? Let’s take a look. Consider the following figure that has a string and indices marked on top and bottom.

Note: Indices on the bottom denote the negative indices.

using negative index

Let’s take a look at how we can fetch substring using negative indices. Let’s say we have to fetch the substring scale. Assuming:

S = Welcome to scaler

The syntax for fetching substring using negative indices would be: S[-6 : -1] OR

sliceObject = slice(-6, -1) => S[sliceObject]

(-6th index points to the 6th element from the end and -1 to the 1st element from the end)

Note: Refer to figure-1 along with the examples in order to understand character-index mapping.

Example 3 – Fetching substring using negative index and negative step value

Output:

Example 4 – Slicing with positive and negative index

Output:

Reversing a substring using a negative ‘step’ in a slice

There are multiple ways by which string slicing in Python can allow us to reverse a string. Slicing is one of the ways that allows us to reverse a string. The ‘Step’ parameter is considered to be less than 0 when reversing a string.

NOTE: When reversing: ‘step’ < 0, ‘start’ > ‘stop’ in slice(start, stop, step). Whereas when not reversing: when ‘step’ > 0, startIndex < stopIndex in slice(start, stop, step)

Let’s look at multiple examples of how reversing can be done using slice:

Example 5 – Reversing a substring using a negative step

Output:

Slice operation on lists and tuple

The way the ‘slice’ operation works on lists and tuples is similar to how it works with strings. A String is a sequential collection of characters where each character has an index similarly; a ‘list’ or a ‘tuple’ is an ordered collection of any specific type of data. Either way, slicing can be performed on any ordered collection of elements.

Let’s see some of the examples on slicing sets and tuples to fetch sub-lists and sub-tuples, respectively.

Consider the following figure:

slice operation on lists and tuples

Note: Please refer to Figure-2 in order to understand the index-element mapping in the code snippets in Example-6 & Example-7.

Example 6 – Performing slice operations on a List to fetch sub-lists

Output:

Example 7 – Performing slice operations on a Tuple to fetch sub-tuples

Output:

It is clear that slice operation slices elements of a collection.The Collection here can be considered as a sequence of characters forming a string OR a list of elements OR a tuple of elements. Irrespective of what the ordered collection has, you can perform slicing on such a collection to fetch a sub-collection.

Conclusion

Let’s recall what string slicing in Python is in a nutshell:

  • Slice() is a pretty versatile operation that has numerous combinations to offer when fetching sub-collections out of a collection.
  • Slice has two different syntaxes:
    • One where a slice() object is created i.e. slice(stop) OR slice(start, stop, step).
    • Another is the shorthand property, i.e. String[start:stop], which is easier to use and execute.
  • ‘Start’ determines the index from which the slice operation will begin.
  • ‘Stop’ determines the index until which slicing is to be performed. Elements right before the ‘stop’ index is to be considered.
  • ‘Step’ defines the steps when iterating the list i.e. it allows us to skip over elements.
  • Indices and steps can have a negative value.

If we consider an analogy, string slicing in Python is no different than slicing an actual loaf of bread in the real world. It’s the same feeling as the operation. Isn’t it?

Python provides us with multiple syntactically readable and elegant operators and methods, slice is one good example. It has many combinations of outcomes to offer, only if we learn to apply and execute this operator and make use of its parameters. Understand and apply slices wherever required as such elegant syntaxes result in clean and quality code.

Read More:

  1. How to reverse a string in Python?
  2. What is split function in python?
  3. What is the list of methods in python?
  4. index() function in Python