0

I need to write a function that takes a string (str), and two other strings (call it replace1 and replace2), and an integer (n). The function shall return a new string, where all the string inputs from replace1 in the first string (str) and replace the new string with replace1 depending on where you want the new input. I am not supposed to use built-in functions, but I can use lens (we can suppose that replace1 has the length 1). Example ( call it replaceChoice):

>>> replaceChoice(“Mississippi”, “s”, “l”, 2)
'Mislissippi'

I hope that I explained it well. Here is my attempt:

def replaceChoice(str1, replace1,n): 
newString=""
  for x in str:
      if x=="str1":
        newString=newString+replace 
  else:
       newString=newString+x 
  return newString
4
  • Where is the replace2 parameter in your attempt? Commented Sep 10, 2016 at 9:36
  • What happens when you call your function as you've written it there? I suspect not much even if the indentation is fixed, because it'll error when it reaches newString=newString+replace because you don't pass replace as an argument Commented Sep 10, 2016 at 9:38
  • You also don't indicate explicitly what you use the integer argument n for, though it looks like it's the position you want to insert (i.e. your example should replace the second s in the string with the proposed character). Obvious homework is obvious. Commented Sep 10, 2016 at 9:39
  • @The_nice_doge you should accept the answer if it answers your question. Commented Sep 10, 2016 at 14:33

1 Answer 1

1

I assume from your question that you want to replace the nth occurrence of r1 with r2. Is this what you want?

>>> def replaceChoice(str1, r1, r2, n):
...     new_str = ""
...     replaced = False
...     for i in str1:
...             if i==r1:
...                     n-=1
...             if n==0 and not replaced:
...                     replaced = True
...                     new_str+=r2
...             else:
...                     new_str+=i
...     return new_str
... 
>>> replaceChoice("Mississippi", "s", "l", 2)
'Mislissippi'
Sign up to request clarification or add additional context in comments.

2 Comments

Strictly speaking range is a python built in function. You can do it with for i in str1 and swap out the value of i withr2 when n == 0
@RolfofSaxony Edited.

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.