abc
abc

Reputation: 429

Remove multiple words from string using list of indexes

sentence = 'Two Dogs and Three Cats'

list_of_indices = [[0,3], [13, 18]]

I wish to remove multiple indices from a string based on its index position by referencing a nested list of index values (which may have more than 2 elements).

I am able to remove a single index range from the string (e.g remove the word Two from the sentence using S = sentence[:0] + sentence[3:] but how do I modify this code to remove multiple range of indices by referencing list_of_indices?

I tried one other method:

to_remove = []

for i in list_of_indices:
    word = sentence[i[0]: i[1]]
    to_remove.append(word)

resultwords  = [word for word in sentence.split() if word not in to_remove]
print(resultwords)
result = ' '.join(resultwords)
print(result)

However, it would not work if the word contains other symbols in the sentence e.g. for sentence = ':Two: Dogs and Three Cats', it would not remove Two

Upvotes: 0

Views: 463

Answers (3)

Y.T.
Y.T.

Reputation: 2739

If complexity isn't a concern, here is an O(NM) approach with the method you suggested, where N is the length of sentence, M is the length of list_of_indices. But be aware of the extraneous space introduced between words that you might want to take care of.

sentence = 'Two Dogs and Three Cats'

list_of_indices = [[0,3], [13, 18]]


for indices in reversed(list_of_indices):
    sentence = sentence[:indices[0]] + sentence[indices[1]:]

print(sentence)

output:

Dogs and  Cats

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54698

The key, I think, is not to think about removing, but to think about what you're keeping.

sentence = 'Two Dogs and Three Cats'
list_of_indices = [[0,3], [13, 18]]

keep = []
last = 0
for a,b in list_of_indices:
    keep.append( sentence[last:a] )
    last = b
keep.append(sentence[last:])
print( ''.join(keep) )

Output:

 Dogs and Cats

Upvotes: 2

Random_Pythoneer59
Random_Pythoneer59

Reputation: 728

You could convert it to a list then add the letters based on index to a new string:

word = 'Hello'
indices = [0, 4]

word_list = list(word)
new_word = ''
for index, value in enumerate(word_list):
    if not index in indices:
        new_word += value

print(new_word)

Output:

ell

Upvotes: -1

Related Questions