首页 > 解决方案 > remove charcaters from string

问题描述

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

标签: pythonstring

解决方案


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

推荐阅读