Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove charcaters from string

Tags:

python

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])
like image 214
moe assal Avatar asked Mar 03 '23 10:03

moe assal


2 Answers

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
like image 54
Imtinan Azhar Avatar answered Mar 12 '23 08:03

Imtinan Azhar


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])
like image 31
kaivalya Avatar answered Mar 12 '23 07:03

kaivalya