i need a function remove()
that removes characters from a string.
This was my first approach:
def remove(self, string, index):
return string[0:index] + string[index + 1:]
def remove_indexes(self, string, indexes):
for index in indexes:
string = self.remove(string, index)
return string
Where I pass the indexes I want to remove in an array, but once I remove a character, the whole indexes change.
Is there a more pythonic whay to do this. it would be more preffarable to implement it like that:
"hello".remove([1, 2])
I dont know about a "pythonic" way, but you can achieve this. If you can ensure that in remove_indexes
the indexes are always sorted, then you may do this
def remove_indexes(self, string, indexes):
for index in indexes.reverse():
string = self.remove(string, index)
return string
If you cant ensure that then just do
def remove_indexes(self, string, indexes):
for index in indexes.sort(reverse=True):
string = self.remove(string, index)
return string
I think below code will work for you.It removes the indexes(that you want to remove from string) and returns joined string formed with remaining indexes.
def remove_indexes(string,indexes):
return "".join([string[i] for i in range(len(string)) if i not in indexes])
remove_indexes("hello",[1,2])
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