Python – Delete Substring defined by Start and End positions in String

Delete Substring from String

Given a string myStr, and start and end index positions of the substring, we need a string created from the string myStr but without the substring that spans from the given start position to end position.

To delete the substring from a string from specific start position to end position in Python, we can use string slicing technique.

Slice a string from starting to just before the specified start index, and slice another string from after the specified end index till the end. Join these two strings, and the resulting string is the original string without the substring.

Syntax

The syntax of the expression to get the string myStr without the substring ranging from start position to end position using slicing is

myStr[:start] + myStr[end + 1: ]

Example

In the following program, we take a string in myStr and delete the substring from start=3 to end=10.

Python Program

myStr = 'abcdefghijklmnopqrstuvwxyz'
start = 3
end = 10
output = myStr[:start] + myStr[end + 1: ]

print(f'Input  : {myStr}')
print(f'Output : {output}')
Run Code Copy

Output

Input  : abcdefghijklmnopqrstuvwxyz
Output : abclmnopqrstuvwxyz

Summary

In this tutorial of Python Examples, we learned how to remove the substring spanning from a specific start index to specific end index from the string using slicing technique, with the help of well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍