同时 .replace 功能 [英] Simultaneous .replace functionality
问题描述
我已经将用户输入的DNA代码(A,T,G,C)
转换成RNA代码(A,U,G,C)
.这很容易
RNA_Code=DNA_Code.replace('T','U')
现在我需要做的下一件事是将 RNA_Code 转换成它的互补链.这意味着我需要用 U 替换 A,用 A 替换 U,用 C 替换 G,用 G 替换 C,但所有这些都是同时发生的.
如果我说
RNA_Code.replace('A','U')RNA_Code.replace('U','A')
它将所有的 As 转换为 Us,然后将所有的 Us 转换为 As,但我只剩下所有的 As.
我需要它把类似 AUUUGCGGCAAA
的东西转换成 UAAACGCCGUUU
.
关于如何完成这项工作的任何想法?(3.3)
使用翻译表:
RNA_compliment = {ord('A'):'U', ord('U'):'A',ord('G'):'C', ord('C'):'G'}RNA_Code.translate(RNA_compliment)
str.translate()
方法 获取从代码点(数字)到替换字符的映射.ord()
函数 给了我们一个给定字符的代码点,可以轻松构建您的地图.
演示:
<预><代码>>>>RNA_compliment = {ord('A'):'U', ord('U'):'A', ord('G'):'C', ord('C'):'G'}>>>'AUUUGCGGCAAA'.translate(RNA_compliment)'UAAACGCCGUUU'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)
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'
这篇关于同时 .replace 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!