Replace input strings and integers
<p>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):</p>

<pre><code>&gt;&gt;&gt; replaceChoice(âMississippiâ, âsâ, âlâ, 2)
'Mislissippi'
</code></pre>

<p>I hope that I explained it well. Here is my attempt:</p>

<pre><code>def replaceChoice(str1, replace1,n): 
newString=""
  for x in str:
      if x=="str1":
        newString=newString+replace 
  else:
       newString=newString+x 
  return newString
</code></pre>

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

<pre><code>&gt;&gt;&gt; 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
... 
&gt;&gt;&gt; replaceChoice("Mississippi", "s", "l", 2)
'Mislissippi'
</code></pre>

python