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
"crane".replace("a", "o", 1)? Where the third argument i.e.1is the count of replacementafter = word[pos+1:], where does the1come 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?)