Search code examples
pythonstringoperator-overloadingmutable

Overloading the del operator in a mutable string class python


I am having a hard time editing the built in del operator and meeting the constraints of my assignment.

In my python class my professor would like us to start with a class created to make strings mutable named Mutstr. In an instance of Mutstr that contains the string "oogyboogy", in three del commands he wants us to get rid of the "gyb" in the string "oogyboogy".

Sigh. Such a poorly constructed assignment... anyway.

I have two code snippets below that accomplish the getting rid of the "gyb".

Unfortunately both of my versions rely on a single del command. I believe my professor wants three separate calls to delete these each index by index.

Whats the best way to march through the entirety of the string evaluating each index to check if it's a specific member of the characters 'gyb' in the middle of the "oogyboogy"

Right now both of these work when I run this:

>>> one = Mutstr('oogyboogy')
>>> del one[2]
>>> one.get()
'oooogy'

Which is I think to be the correct answer. However, I think its the way I accomplish it that does not meet his problem constraints:

class Mutstr():
    def __init__(self,st = ""):
          self.str = st

    def get(self):
          return self.str

    def __delitem__(self, index):
          self.str = self.str[:index] + self.str[index+3:]

I have another version that does the same here:

    def __delitem__(self, index):
      if 'g' in self.str:
          self.str = self.str[:index] + self.str[index+1:]
      if 'y' in self.str:
          self.str = self.str[:index] + self.str[index+1:]
      if 'b' in self.str:
          self.str = self.str[:index] + self.str[index+1:]

Solution

  • The way I am reading the assignment, your professor is probably looking for something like:

    class Mutstr(object):
        def __init__(self, st=""):
              self.st = st
    
        def get(self):
              return self.st
    
        def __delitem__(self, index):
              self.st = self.st[:index] + self.st[index+1:]
    
    one = Mutstr('oogyboogy')
    del one[4]
    del one[3]
    del one[2]
    print one.get()