patternpythonModerate
Reverse complement of a DNA string
Viewed 0 times
complementstringdnareverse
Problem
I have a function in python where I want the reverse complement of a DNA string.
This is what I have now:
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
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')Solution
You can do this with
But here is how you'd use it in Python 2:
And here is how you can use it in Python 3:
You can re-implement this yourself, but the above is written in C, and so should out perform any Python code.
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:
>>> import string
>>> trans = string.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'And here is how you can use it in Python 3:
>>> trans = str.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'
>>> trans = {ord('A'): 'T', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
>>> '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.
Code Snippets
>>> import string
>>> trans = string.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'>>> trans = str.maketrans('ATGC', 'TACG')
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'
>>> trans = {ord('A'): 'T', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
>>> 'ATTAGCC'.translate(trans)
'TAATCGG'Context
StackExchange Code Review Q#151329, answer score: 11
Revisions (0)
No revisions yet.