Remove parts of string based on list of index chunks

Viewed 47

I have a list of index 'chunks' that I need to remove from a string. An example:

list_to_remove = [(0, 4), (10, 14)]

test_text = "This is a test sentence"

The removal should be characters from index 0 to 4, and characters from index 10 to 14.

After removal the result should be:

test_text_clean = "is a sentence"

I have thought about looping through the chunks in the list and slicing the string, however removing something from the string would change the position of the remaining characters, meaning my indexes would no longer be correct for the remaining removals.

2 Answers

You could loop and slice from the end to avoid changing the indices of the sections to remove, just reverse list_to_remove

list_to_remove = [(0, 4), (10, 14)]
test_text = "This is a test sentence"
for t in list_to_remove[::-1]:
    test_text = test_text[:t[0]] + test_text[t[1] + 1:]
print(test_text) # is a sentence

You can do it like this, it won't be super efficient since you are iterating over individual characters but it should work:

clean_text = ''.join(
    i for index,i in enumerate(test_text) if not any(
        j[0]<=index<j[1] for j in list_to_remove
    )
)
Related