Reverse complement of a DNA string I have a function in python where I want the reverse complement of a DNA string.

This is what I have now:

def inversComplement(input):
    output = ''
    for letter in input:
        letter = letter.upper()

        if letter == 'A':
            output += 'T'
        elif letter == 'T':
            output += 'A'
        elif letter == 'G':
            output += 'C'
        else:
            output += 'G'

    return(output[::-1])


I was thinking of using the string.replace() method. But the problem was that if I use this the T-> A would be changed afterwards with the A -> T replacement


    string.replace('A','T').replace('T','A').replace('G','C').replace('C','G')
You can do this with str.translate, which was changed slightly in Python  3. All you need to do is pass it a translation table, and it'll do what your above code is doing. However to build the translation table is hard in Python 2 and requires the helper function string.maketrans, which was changed to str.maketrans in Python 3.

But here is how you'd use it in Python 2:

&gt;&gt;&gt; import string
&gt;&gt;&gt; trans = string.maketrans('ATGC', 'TACG')
&gt;&gt;&gt; 'ATTAGCC'.translate(trans)
'TAATCGG'


And here is how you can use it in Python 3:

&gt;&gt;&gt; trans = str.maketrans('ATGC', 'TACG')
&gt;&gt;&gt; 'ATTAGCC'.translate(trans)
'TAATCGG'
&gt;&gt;&gt; trans = {ord('A'): 'T', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
&gt;&gt;&gt; 'ATTAGCC'.translate(trans)
'TAATCGG'


You can re-implement this yourself, but the above is written in C, and so should out perform any Python code.