delete substrings by given list of pairs of indices

  • Last Update :
  • Techknowledgy :

Given an unordered, potentially overlapped list of ranges:

blocks = [(5, 7), (2, 4), (6, 10)]

I want to convert this into:

exclude = {


exclude = set()
for block in blocks:
   exclude.update(range( * block))

To really answer Mai's question, I implemented delete_substring_blocks using delete_blocks:

def delete_substring_blocks(s, blocks):
   return ''.join(delete_blocks(s, blocks))

A relatively inefficient expression, but one that will handle overlapping and non-sorted blocks, is:

def delete_substring_blocks(s, blocks):
   return ''.join(
         for i, c in enumerate(s)
         if not any(blk
            for blk in blocks
            if i >= blk[0] and i < blk[1])

Here is an example with an overlapping block:

>>> delete_substring_blocks(
   "hello there how are you",
      [0, 3],
      [7, 9],
      [7, 10]
'lo te how are you'

As you appear to find this expression unreadable, here it is broken down a little more:

def delete_substring_blocks(s, blocks):
   def check_pos(i):
   return not any(1
      for start, end in blocks
      if i >= start and i < end)

return ''.join([c
   for i, c in enumerate(s)
   if check_pos(i)

It would be something like:

def delete_substring_blocks(s, blocks):
s: original input string
blocks: list of indices(start, end) to be deleted

return string `out`
where blocks are deleted from orig_str
for start, end in reversed(sorted(blocks)):
   s = s[: start] + s[end: ]
return s

This is a solution based on a bitmap. It can handle overlapping blocks:

def delete_substring_blocks(s, blocks):
   # create a bitmap with False
for characters to be deleted
preserve = [True] * len(s)
for i, j in blocks:
   preserve[i: j] = False

result = []
for i, c in enumerate(s):
   if preserve[i]:

return ''.join(result)

No. What you're asking for is fairly specific. You could easily one line it if you wanted to specify the parts of the string you wanted to keep (as opposed to delete).

>>> string = 'my long string' >>>
   ''.join([string[s: e]
      for s, e in [(0, 3), (8, 14)]
'my string'

Suggestion : 2

Last Updated : 31 May, 2021,GATE CS 2021 Syllabus


Suggestion : 3

1.  First occurrence of part string ‘abc’ found at index 2 so remove it. After that, the resultant string becomes dabaabcbc.,2. Found the next occurrence of part string ‘abc’ at index 4 so remove it. After that, the resultant string becomes dababc.,3. Found the next occurrence of part string ‘abc’ at index 3 so remove that part. After that, the resultant string becomes dab.,4.  Now, there are no occurrences of part string present in the final string so return the resultant string as an output.


   class Solution {

      public String removeOccurrences(String s, String part) {

         if (part.length() == 0 || part.length() > s.length())
            return s;
         int occIndex = s.indexOf(part);
         while (occIndex != -1) {
            s = s.substring(0, occIndex).concat(s.substring(occIndex + part.length()));
            occIndex = s.indexOf(part);
         return s;

  C++ Program of Remove All Occurrences of a Substring

 class Solution {
    public: string removeOccurrences(string s, string part) {
       int i = 0;
       int len = s.length();
       string finalRes = s;
       while (i < len) {
          string s = finalRes;
          if (s.find(part) < s.length()) {
             int occInd = s.find(part);
             finalRes.erase(occInd, part.length());
       return finalRes;

Suggestion : 4

Python Program for removing i-th character from a string,In this tutorial, we will learn to remove the i-th character from a string in Python. Strings in Python are a sequence of characters wrapped in single, double, or triple quotes. For a given string, we have to remove the character present at the i-th index in the string. Indexing in a string starts from 0.,We have seen two different approaches for removing the i-th character in a string. The first approach is by splitting the string into two halves to remove the i-th character. The second is by using the replace() method of string class.,In the function, since indexing in a string starts with 0, to remove i-th character, we have to pass i-1 as an index.

We have sliced the string into two substrings and stored each substring in another variable then we have joined the two substrings using the concatenation operator (+). Since, indexing in a string starts with 0, to remove i-th character, we have to pass i-1 as an index in our function.

def remove_char(s, i):
   a = s[: i]
b = s[i + 1: ]

return a + b

string = "Pythonisgood"
# Remove ith index element
i = 5
print(remove_char(string, i - 1))

In the function, since indexing in a string starts with 0, to remove i-th character, we have to pass i-1 as an index.

def remove_char(s, i):

   for j in range(len(s)):
   if j == i:
   s = s.replace(s[i], "", 1)
return s

string = "Welcome"
# Remove i - th index element
i = 2
print(remove_char(string, i - 1))

Suggestion : 5

If we output the element at index 3, we get:,We can also remove elements from a list by assigning an empty list to them:,After we execute these assignment statements,If you try to access or assign to an element that does not exist, you get a runtime error:

ps = [10, 20, 30, 40]
qs = ["spam", "bungee", "swallow"]
zs = ["hello", 2.0, 5, [10, 20]]
>>> vocabulary = ["apple", "cheese", "dog"] >>>
   numbers = [17, 123] >>>
   an_empty_list = [] >>>
   print(vocabulary, numbers, an_empty_list)["apple", "cheese", "dog"][17, 123][]