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?
Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.
To remove multiple characters from a string we can easily use the function str. replace and pass a parameter multiple characters. The String class (Str) provides a method to replace(old_str, new_str) to replace the sub-strings in a string. It replaces all the elements of the old sub-string with the new sub-string.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With