Removing substring from string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wrobl1rt
    New Member
    • Nov 2009
    • 1

    Removing substring from string

    I am trying to remove a specific substring from a string... Here are the doctests that are supposed to pass. I'm just absolutely stumped. Can someone point me in the right direction on where to start?

    def remove(sub, s):

    """
    >>> remove('an', 'banana')
    'bana'
    >>> remove('cyc', 'bicycle')
    'bile'
    >>> remove('iss', 'Mississippi')
    'Mippi'
    """


    def remove_all(sub, s):
    """
    >>> remove('an', 'banana')
    'ba'
    >>> remove('cyc', 'bicycle')
    'bile'
    >>> remove('iss', 'Mississippi')
    'Mippi'
    """


    if __name__ == '__main__':
    import doctest
    doctest.testmod ()
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I don't understand the question. Surely it's not as simple as this:
    Code:
    >>> 'banana'.replace('an', '')
    'ba'
    >>> 'banana'.replace('an', '', 1)
    'bana'
    >>> 'Mississippi'.replace('iss', '')
    'Mippi'
    >>> 'Mississippi'.replace('iss', '', 1)
    'Missippi'
    >>>

    Comment

    • mrkozma
      New Member
      • Jan 2015
      • 1

      #3
      This is one solution for remove_all:
      Code:
      import string
      
      def remove_all(substr, str):
          index = 0
          length = len(substr)
          while string.find(str, substr) != -1:
              index = string.find(str, substr)
              str = str[0:index] + str[index+length:]
          return str

      Comment

      Working...