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 
4
  • 1
    Why not just "crane".replace("a", "o", 1)? Where the third argument i.e. 1 is the count of replacement Commented Nov 28, 2020 at 5:49
  • Hello. Looks like regex might help here. Look at this once to see if it helps - stackoverflow.com/a/3951684/4162268. Commented Nov 28, 2020 at 5: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?) Commented Nov 28, 2020 at 6:10
  • Does this answer your question? Replace first occurrence of string in Python Commented Jan 12, 2021 at 18:20

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

after = word[pos+len(a):]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.