Python | Slice operator | List | String | Tuple

Introduction

In this tutorial, we are going to study how to use the slice operator in python. The slice operator is used to slice the string i.e [n:m] it will return the part of the string starting from the nth character to the mth character including the first but excluding the last. The slice() in python is used for a similar purpose.

What is slicing?

Slicing means getting the substring(subpart) from the string(or an iterable). It is done in python with the help of brackets[]. It helps to get access to the parts of sequences like strings, tuples, and the list. Slicing syntax comes with three parameters start, stop and step.

Slice operator

slice[start:stop:step]

start: Starting index where the slicing of the object starts

stop: Ending index where the slicing of the object is stopped

step: This argument determines the increment between each index for slicing

More ways to use the slice operator:

#slicing done from start index to stop index -1
Slice[start:stop]

#slicing from start index to the end
slice[start:]

#slicing done from the beginning to index stop-1
Slice[:stop]

Examples of Slice operator in Python

Example 1:

string1 = 'Welcome to copyassignment.com?'
print("String = ",string1)

# Slice

print("Slicing from start index to stop-1 = ",string1[4:8])
print("Slicing from start index to the end = ",string1[6:])
print("Slicing from the beginning to index stop - 1 = ",string1[:5])
print("Slicing from the start index to stop index, by skipping step = ",string1[5:11:2])

Output 1:

Output 1 of slice operator in Python

Example 2:

string1 = 'Welcome to copyassignment.com?'
print("String = ",string1)

# Slice
print("String after slicing and using step = ",string1[4:12:2])

Output 2:

Output 2 of slice operator in Python

Example 3:

We can perform the slicing on the tuples and use the step parameter to do the increment between the indexes.

# Create a Tuple
tuplelist = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October")
print("Tuple = ",tuplelist)

# Slice the Tuple 
print("Tuple after slicing = ",tuplelist[2:8:2])

Output 3:

Output 3 of slice operator in Python

Example 4:

We can perform the slicing on the different parts and also use step parameters to set the increment index.

# Create a List
Lists = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
print("List = ",Lists)

# Slice the List
print("List after slicing = ",Lists[2:9:3])

Output 4:

Output 3 of slice operator in Python

Click here to get more information on slice operator.

Thank you for visiting our website.


Also Read:

Share:

Author: pranjal dev