Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

python - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...