What is String Slicing in Python?

Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences, such as lists. Slices can also be applied on third-party objects like NumPy arrays and Pandas series and data frames.

Slicing in Python

Syntax

Syntax: slice(start, end, step)

Parameter
Description
start
(Optional) An integer number specifying at which position to start the slicing. Default is 0.

end
An integer number specifying at which position to end the slicing.

step (Optional) An integer number specifying the step of the slicing. Default is 1.

Example

a=("a", "b", "c", "d", "e", "f", "g", "h")
x=slice(0, 5, 2)
print(a[x])

Output

("a","b","e")

Explanation

a = ("a","b","c","d","e","f","g","h")
x = slice(0, 5, 2)

Let's split it into 2 parts

Part 1

Slice (0,5)
This means it wants you to slice from the 0th element to the 4th element
(5-1)

Hence, print from a to e (a, b, c, d, e) will be the output

Part 2

a = ("a", "b", "c", "d", "e", "f", "g", "h")
Slice (0,5,2)


Here, it will have a stride of 2, meaning it will jump 2 elements.
0th elements, (0+2)th element, (0+2+2)th element which is a, c, e

Hence, we get the output as ("a", "c", "e")


So, that was Slicing in Python. I hope this article helped you get a good grasp of it.

Courses: 

  1. Introduction To Python Programming
  2. Python Boot camp 2021: Build 15 working Applications and Games
  3. Decision Trees, Random Forests, AdaBoost & XGBoost in Python

Comments