Q:

There is something wrong with my Python code involve the replace function

I was creating a function about replacing multiple part of a string with multiple number but for some reason, the output is not what i expected.
from pyprimes import isprime
def prime_replace(x, l = []):
    lst = []
    string = str(x)
    for n in range(10):
        for i in l:
            string = string.replace(string[i], str(n))
        lst.append(int(string))
    return lst 

print prime_replace(x = 56243, l = [2, 3])

The output of this function is a list [56003, 56113, 56223, 56333, 56444, 56555, 66666, 77777, 88888, 99999] but what i wanted is [56003, 56113, 56223, 56333, 56443, 56553, 56663, 56773, 56883, 56993] Can someone help me with this and tell me what went wrong, thank you.

A:

You're modifying the original string, and replace is replacing "all occurrences"
Here's part of a print out for how it's generating the output you see:
...
string is now 56333
replacing 3 with 3
string is now 56333
replacing 3 with 4
string is now 56444
...

You can see that we successfully got 56333 like you wanted, but then you wanted to replace str[2] (actual value: 3) with str(n) (actual value: 4), which replaced all occurrences of 3
One workaround for this specific scenario is to make a copy of your string:
def prime_replace(x, l = []):
    lst = []
    string = str(x)
    for n in range(10):
        newstr = string
        for i in l:
            newstr = newstr.replace(string[i], str(n))
        lst.append(int(newstr))
    return lst 

print prime_replace(x = 56243, l = [2, 3])

Output:
[56003, 56113, 56223, 56333, 56443, 56553, 56663, 56773, 56883, 56993]

Demo (not recommended)
However, replace may not be the best choice since it will replace all occurrences of the "oldstring" with the "newstring". It looks like what you're really trying to do is to change string at indices in l to be the next value in range(10), we can do this through indexing and appending:
def prime_replace(x, l = []):
    lst = []
    string = str(x)
    for n in range(10):
        newstr = string
        for i in l:
            newstr = newstr[0:i]+str(n)+newstr[i+1:];
        lst.append(int(newstr))
    return lst 

Demo (better)

