How to Slice a String [Substring] in Python

Here are the examples of String slicing in Python. Below examples demonstrates how to use positive and negative slicing . These examples tell what the result will be for single and double colon operators.


Python index for string occurrence first, last and so on

The index for the first occurrence is zero and increments one towards the right. The index from the last element is as follows -1 -2 , -3 and so on.

Python string index

Read: Positive string Slicing examples in Python

Negative slice

The index for the last elements is ‘-1’. Below the example, I will use minus slice and explain how it works.

s = 'Shenanigan'

The output


** Process exited - Return Code: 0 **

The length value has -4. That means towards the left side, after -4th digit, it displays the string. So in the display, we got the ‘Shenan’ substring.

Python string slicing

Negative index on both the sides of the colon

string = "freecodecamp"

The output


** Process exited - Return Code: 0 **

Here, length starts from -4, which means ‘c’ towards the left side. The length parameter after the colon is -1, which means it ignores the last element. So the final output is the cam.

String slices with two colons

This is an advanced slicing method in python. Where in you can use double slicing operators. Let us see how it works.

s = 'Shenanigan'

The output


** Process exited - Return Code: 0 **

Here, in the first step [0:10], it prints the entire string. After the second colon, the ‘2’ tells to print every second element. So the final output is Seaia.

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.