Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous .replace functionality

I have already converted user input of DNA code (A,T,G,C) into RNA code(A,U,G,C). This was fairly easy

RNA_Code=DNA_Code.replace('T','U')

Now the next thing I need to do is convert the RNA_Code into it's compliment strand. This means I need to replace A with U, U with A, G with C and C with G, but all simultaneously.

if I say

RNA_Code.replace('A','U')
RNA_Code.replace('U','A')

it converts all the As into Us then all the Us into As but I am left with all As for both.

I need it to take something like AUUUGCGGCAAA and convert it to UAAACGCCGUUU.

Any ideas on how to get this done?(3.3)

like image 269
Deaven Morris Avatar asked May 01 '13 17:05

Deaven Morris


1 Answers

Use a translation table:

RNA_compliment = {
    ord('A'): 'U', ord('U'): 'A',
    ord('G'): 'C', ord('C'): 'G'}

RNA_Code.translate(RNA_compliment)

The str.translate() method takes a mapping from codepoint (a number) to replacement character. The ord() function gives us a codepoint for a given character, making it easy to build your map.

Demo:

>>> RNA_compliment = {ord('A'): 'U', ord('U'): 'A', ord('G'): 'C', ord('C'): 'G'}
>>> 'AUUUGCGGCAAA'.translate(RNA_compliment)
'UAAACGCCGUUU'
like image 167
Martijn Pieters Avatar answered Sep 18 '22 07:09

Martijn Pieters