Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple indices of a string

Tags:

python

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?

like image 971
embert Avatar asked Apr 26 '14 07:04

embert


People also ask

How do I remove multiple indices from a list?

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.

How do I remove multiple elements from a string in Python?

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.


1 Answers

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])

like image 118
thefourtheye Avatar answered Sep 21 '22 17:09

thefourtheye