Remove multiple indices of a string
python, string
Solution
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])`
Problem
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?