Remove character from a string by index in Python

avatar

Borislav Hadzhiev

Last updated: Jul 8, 2022

banner

Photo from Unsplash

Remove character from a string by index in Python #

Use string slicing to remove a character from a string by index, e.g. result = my_str[:idx] + my_str[idx+1:]. The first slice returns the part of the string before the specified index, and the second slice - the part of the string after the specified index.

main.py
my_str = 'avocado' idx = my_str.index('c') # ✅ remove character from string by index result_1 = my_str[:idx] + my_str[idx+1:] print(result_1) # 👉️ avoado # ✅ remove multiple characters from string by index result_2 = my_str[:idx] + my_str[idx+2:] print(result_2) # 👉️ avodo

We used string slicing to remove a character at a specific index from a string.

You can use the str.index() method if you need to get the index of the character.

The str.index method returns the index of the first occurrence of the provided substring in the string.

The method raises a ValueError if the substring is not found in the string.

The syntax for string slicing is my_str[start:stop:step], where the start value is inclusive, and the stop value is exclusive.
main.py
my_str = 'avocado' idx = my_str.index('c') result_1 = my_str[:idx] + my_str[idx+1:] print(result_1) # 👉️ avoado

The first slice my_str[:idx] selects the part of the string up to (but not including) the specified index.

main.py
my_str = 'avocado' idx = my_str.index('c') print(my_str[:idx]) # 👉️ 'avo' print(my_str[idx + 1:]) # 👉️ 'ado'

The second slice my_str[idx + 1:] starts at the character after the index and goes to the end of the string.

Notice that we added 1 to the index. Since the start value is inclusive, we have to add 1 to omit the character at the index from the result.

You can use this approach to remove multiple characters from a string by index.

main.py
my_str = 'avocado' idx = my_str.index('c') # ✅ remove multiple characters from string by index result_2 = my_str[:idx] + my_str[idx+2:] print(result_2) # 👉️ avodo

The example adds 2 to the start value in the second slice, so we end up removing 2 characters from the string.

Since Python strings are immutable, the only way to remove a character from a string is to create a new string that doesn't contain the character.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.