embert
embert

Reputation: 7592

Remove multiple indices of a string

What would be a good and short approach to remove a list of indices from a string?

The point is, if I remove a char at index, the indices of the string shift. In this case I would need to shift all the indices in the list, too. Is this the right way or is there a more straight forward approach?

Upvotes: 10

Views: 5706

Answers (2)

astromancer
astromancer

Reputation: 611

You can use the builtin bytearray for this

def delete(string, indices):
    z = bytearray(string.encode())
    for i in sorted(indices, key=abs, reverse=True):
        del z[i]
    return z.decode()

delete('Hello world!', [0, -3])

'ello word!'

Beware that this will only work for ascii character strings where the str -> byte mapping is one-to-one.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

Strings are immutable. So deleting elements from it will not work.

data = "Welcome"
del data[0]
# TypeError: 'str' object doesn't support item deletion

The best way is to reconstruct the string without the elements from the specific indexes and join them together, like this

data, indexes = "Welcome", {1, 3, 5}
print "".join([char for idx, char in enumerate(data) if idx not in indexes])
# Wloe

Note that the indexes is a set of numbers, since sets offer faster lookup than the lists. If you have a list of numbers like [1, 3, 5] and if you want to convert them to a set, use set function to do that, like this set([1, 3, 5])

Upvotes: 15

Related Questions