String Slicing

Python’s String slicing is a versatile feature that allows you to extract a part of a string, or alter pieces of it. It’s a common operation that comes in handy when working with text data in Python.

Basic String Slicing

In Python, strings are indexed with all the characters having an assigned number - the index. The index number starts from 0 and goes up to n-1, where n is the length of the string.

Let’s look at a string slicing example in Python:

1s = "Hello, World!"

In this case, the output will be Hello. The slice starts from the index position 0 (H) and goes up to the index position 4 (o), excluding the end index.

We can even omit the start or end index, and Python will slice the string from the beginning or up to the end, respectively.

1s = "Hello, World!"

This code will output World! and Hello, respectively.

Negative Indexing in String Slicing

Python also supports negative indexing, which starts from the end of the string. The last character is assigned an index of -1, the second last -2, and so forth.

This is particularly useful when we want to slice a string from the end.

1s = "Hello, World!"

This code will output ! and World, respectively.


The concept of string slicing also applies to other sequence data types in Python such as lists and tuples.

Skipping Characters While Slicing

In Python, we can even skip characters while slicing a string. This is done by providing a third index, known as the step value.

For example, if we want to print every second character of a string, we can do so as follows:

1s = "Hello, World!"

This code will output Hlo ol!.

The ::2 in the square brackets tells Python to return every second character of the string s from the start to the end.

Slicing a string ’s’ in Python provides us with a new string that is a subset of ’s’. It’s a powerful way to handle and manipulate strings in Python.