Weird behavior in Python
Question: I wrote a simple program to translate DNA to RNA. Basically, you input a
string, it separates the string into characters and sends them to a list,
shifts the letter and returns a string from the resulting list. This program
correctly translates a to u, and to to a, but does not change g to c and c to
g.

This is the program:

    
    
    def trad(x):
    
        h=[]
        for letter in x:
            h.append(letter)
        for letter in h:
            if letter=="a":
                h[h.index(letter)]="u"
                continue
            if letter=="t":
                h[h.index(letter)]="a"
                continue
            if letter=="g":
                h[h.index(letter)]="c"
                continue
            if letter=="c":
                h[h.index(letter)]="g"
                continue
        ret=""
        for letter in h:
            ret+=letter
        return ret
    
    while True:
        stry=raw_input("String?")
        print trad(stry)
    

Now, just altering the program by not iterating over elements, but on
positions, it works as expected. This is the resulting code:

    
    
    def trad(x):
        h=[]
        for letter in x:
            h.append(letter)
        for letter in xrange (0, len(h)):
            if h[letter]=="a":
                h[letter]="u"
                continue
            if h[letter]=="t":
                h[letter]="a"
                continue
            if h[letter]=="g":
                h[letter]="c"
                continue
            if h[letter]=="c":
                h[letter]="g"
                continue
        ret=""
        for letter in h:
            ret+=letter
        return ret
    
    while True:
        stry=raw_input("String?")
        print trad(stry)
    

Why does this strange behaviour occur, and how can I resolve it?


Answer: You are going about this a much harder way than is necessary, this could
easily be done using
[`str.translate()`](http://docs.python.org/2.7/library/stdtypes.html#str.translate)
\- a method on `str` instances that translates instances of one character to
another, which is exactly what you want:

    
    
    import string
    replacements = string.maketrans("atgc", "uacg")
    while True:
        stry=raw_input("String?")
        print stry.translate(replacements)
    

This is an answer for 2.x, in 3.x, use `str.maketrans()` instead.

