user7742265
user7742265

Reputation:

Remove method for string/words

I am trying to write a method for an item removal in a list based on the target value. Here goes:

def remove (self, target_value):
    str_list = self.str_list
    pos = 0
    for item in str_list:
        if item != target_value:
            str_list[pos] = item
            pos += 1
    del str_list[pos:]
    return str_list

Unfortunately this works only for a single word i.e.

if str_list = apple (it is essentially converted to a list ['a','p','p','l','e'] in my init method)

target_item = 'a'

output = pple.

What changes are needed in order to make it work for several words i.e.

if str_list = I ate an apple

target_item = ate

output = I an apple

PS: No in-built methods are allowed.

Upvotes: 2

Views: 94

Answers (1)

Adonis
Adonis

Reputation: 4818

The straightforward approach is to create an empty list, and push inside every word except the target. Return then that list:

def remove_token(list_val, target_val):
    size=0
    for item in list_val:
         size += 1
    str_list = [None]*size
    pos = 0
    counter_target = 0
    for item in list_val:
        if item != target_val:
            #print(pos)
            str_list[pos] = item
            pos += 1
        else:
            counter_target +=1
    return str_list[:-counter_target]

The below:

print(remove_token(["I", "ate", "an", "apple"], "ate"))

Gives an output:

['I', 'an', 'apple']

Note: Just to make it clear, I am using Python 3.6 (it should work for earlier version besides the print statement (for Python 2.x))

Upvotes: 2

Related Questions