0

I am using a module called introcs to replace the first occurrence of a specified letter. It works well until you ask it to replace two letters. Any advice on how to improve this code? It doesn't work on the last two examples (see below).

def replace_first(word,a,b):
    """
    Returns: a copy of word with the FIRST instance of a replaced by b
    
    Example1: replace_first('crane','a','o') returns 'crone'
    Example2: replace_first('poll','l','o') returns 'pool'
    Example3: replace_first('crane','cr','b') returns 'bane'
    Example4: replace_first('heebee','ee','y') returns 'hybee'
    
    Parameter word: The string to copy and replace
    Precondition: word is a string
    
    Parameter a: The substring to find in word
    Precondition: a is a valid substring of word
    
    Parameter b: The substring to use in place of a
    Precondition: b is a string
    """
    
    pos = introcs.index_str(word,a)
    #print(pos)
    before = word[:pos]
    after  = word[pos+1:]
    #print(before)
    #after  = word[pos+1:]
    #print(after)
    result = before+b+after
    #print(result)
    return result 
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
gs2124
  • 11
  • 2
  • 1
    Why not just `"crane".replace("a", "o", 1)`? Where the third argument i.e. `1` is the count of replacement – Vishnudev Krishnadas Nov 28 '20 at 05:49
  • Hello. Looks like regex might help here. Look at this once to see if it helps - https://stackoverflow.com/a/3951684/4162268. – Nabakamal Das Nov 28 '20 at 05:51
  • 1
    In your own words, when you do `after = word[pos+1:]`, where does the `1` come from? You say that when you try to replace more than one letter, it doesn't work properly. Can you identify a pattern in how it's failing? Can you think of a way to change this line of code, that takes into account how many letters are being replaced? (Hint: can you think of a way to check how many letters are being replaced?) – Karl Knechtel Nov 28 '20 at 06:10
  • Does this answer your question? [Replace first occurrence of string in Python](https://stackoverflow.com/questions/4628618/replace-first-occurrence-of-string-in-python) – Tomerikoo Jan 12 '21 at 18:20

2 Answers2

0

string package has a replace function. You could write a function that replaces the number of occurrences. e.g:

def replaced(word, a, b, replacement_count):
    return word.replace(a, b, replacement_count)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Platos-Child
  • 324
  • 1
  • 6
0

You have to change the definition of after. change it to:

after = word[pos+len(a):]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61