468,321 Members | 1,818 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,321 developers. It's quick & easy.

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()
Nov 2 '09 #1
2 98867
bvdet
2,851 Expert Mod 2GB
I don't understand the question. Surely it's not as simple as this:
Expand|Select|Wrap|Line Numbers
  1. >>> 'banana'.replace('an', '')
  2. 'ba'
  3. >>> 'banana'.replace('an', '', 1)
  4. 'bana'
  5. >>> 'Mississippi'.replace('iss', '')
  6. 'Mippi'
  7. >>> 'Mississippi'.replace('iss', '', 1)
  8. 'Missippi'
  9. >>> 
Nov 2 '09 #2
This is one solution for remove_all:
Expand|Select|Wrap|Line Numbers
  1. import string
  2.  
  3. def remove_all(substr, str):
  4.     index = 0
  5.     length = len(substr)
  6.     while string.find(str, substr) != -1:
  7.         index = string.find(str, substr)
  8.         str = str[0:index] + str[index+length:]
  9.     return str
  10.  
Jan 24 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by becte | last post: by
29 posts views Thread by zoro | last post: by
5 posts views Thread by Isa Janfada | last post: by
3 posts views Thread by jobs | last post: by
6 posts views Thread by lawpoop | last post: by
4 posts views Thread by Jack | last post: by
4 posts views Thread by Ahmed, Shakir | last post: by
reply views Thread by Adam Pletcher | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by howard w | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.