In this article we will discuss how to remove characters from a string at specific index position or in a given range of indices.

We can remove characters from string by slicing the string into pieces and then joining back those pieces.

String Slicing

In Python strings are immutable i.e. we can not modify the string objects. Therefore when we slice a string it returns a new string object instead of modifying then original one.

We can slice a string using operator [] i.e.

It returns a new string object containing parts of given string i.e. it selects a range from start to stop-1 with given step size i.e. interval.

Let’s use slicing to remove characters from a string by index.

Remove a character from string at specific index

Suppose we have a string object i.e.

Let’s remove the character at index 5 in above created string object i.e.

Output:

It deleted the character at index 5 i.e. ‘i’ from ‘is’ in the above string.

As we can not modify the immutable string objects, so to simulate the removal effect we just selected the sub string from index [0 to index) & [index+1 to end), then merged those sub strings and assigned it back to the original string.  Cheeky trick 😉

Now let’s use the same trick to achieve other things i.e.

Remove First Character from a String

Just select the range from index 1 to end and assign it back to original string i.e.

Output:

Remove Last Character from a String

Just select the range from index 0 to end – 1 and assign it back to original string i.e.

Output:

Remove multiple characters from a string in given index range

We can use the same trick to delete the multiple characters from a given string for a given index range.

For example let’s see how to delete the characters in index range 5 to 10 from a given string i.e.

Output:

Complete example is as follows :

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.