Photo by Margaret Jaszowska on Unsplash

Slicing strings in Python

Priyanshu Sahu
3 min readApr 30, 2022

--

Hey there! You must be here to know about “what python slicing is?”, but let us not talk about it technically to understand it better, have a moment for yourself and try to understand what slice means in English. Slice means to cut something to have it out of some whole subject, a part of something.

Just as you take a slice of cheese from your cheese cube, you will be slicing words (strings) in python. Trust me; it is as simple as that.

Python Slicing

In python, you can return a range of words using slicing or, shall I say you, can select a particular slice of that word that you want to use in your program. We will try to understand slicing using both positive and negative inputs

Here in python, you can select items using positive and negative numbers i.e

  • A positive number helps in returning selection from the left-hand side. whereas,
  • A Negative number helps in returning selection from the other end i.e (from right)
  • But, here you can not use “0” to include or exclude for the selection of the set of letters to return.

Slicing using positive numbers

The logic for positive slicing

Observe the code below

This code means that Include all possible selections and exclude nothing from it

Here, it first included the first 5 letters from left viz. P, y, t, h, o and the from selection it excludes the first 2 letters from left viz. P, y and returns t, h, o.

Slicing using negative numbers

Python negative slicing

Here, it first included the first 5 letters from the right viz. n, o,h, t, y, and the from selection it excludes the first 2 letters from the right viz. o, n and returns y, t,h.

Here if you mix the positive and negative numbers to return a slice from the selection, you will confuse the compiler, try to find out what will be the output if you do so. 😉

--

--

Priyanshu Sahu

Hi! I’m Priyanshu Sahu, I am currently pursuing my graduation. The domain Data Science fascinates me the most and I love to exchange knowledge about the same!