How to delete character at specific index in string?
Delete Character at Specific Index in String
Given a string myStr
and an index position index
, we need a string created from the string myStr
but without the character at specified index index
.
To delete the character from a string at specific index in Python, we can use string slicing technique.
Slice a string from starting to just before the specified index, and slice another string from after the specified index till the end. Join these two strings, and the resulting string is the original string without the character at specified index.
Syntax
The syntax of the expression to get the string myStr
without the character at index index
using slicing is
myStr[:index] + myStr[index + 1: ]
Example
In the following program, we take a string in myStr
and delete the character at index=3.
Python Program
myStr = 'apple'
index = 3
output = myStr[:index] + myStr[index + 1: ]
print(f'Input : {myStr}')
print(f'Output : {output}')
Output
Input : apple
Output : appe
Summary
In this tutorial of Python Examples, we learned how to remove the character at a given index from the string using slicing technique, with the help of well detailed examples.