简体   繁体   English

使用 str.translate() 从 DNA 到 RNA

[英]DNA to RNA using str.translate()

I'm trying to convert the DNA code into RNA code using Python...我正在尝试使用 Python 将 DNA 代码转换为 RNA 代码......

I write this:我这样写:

print('Digite a sequência DNA a ser transcrita para RNA:')

my_str = raw_input()
print(my_str.replace('T', 'U'))

And it works, but.. now I need to convert A to U , T to A , G to C and C to G ... I looked how I could do it, and did this:它有效,但是..现在我需要将A转换为 UT 到 AG 到 CC 到 G ......我看看我是怎么做到的,然后这样做了:

print('Digite a sequência DNA a ser transcrita para RNA:')

my_str = raw_input()


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

my_str.translate(RNA_compliment)

But I get this error:但我收到此错误:

Traceback (most recent call last):
  File "rna2.py", line 15, in <module>
    my_str.translate(RNA_compliment)
TypeError: expected a character buffer object

What i did wrong?我做错了什么?

python 3:蟒蛇3:

  • str.maketrans is a static method, which returns a translation table usable for str.translate() . str.maketrans是一个静态方法,它返回一个可用于str.translate()的转换表。
  • If there are two arguments, they must be strings of equal length.如果有两个参数,它们必须是等长的字符串。
i, j = "ATGC", "UACG"

tbl = str.maketrans(i, j)

my_str = "GUTC"

print(my_str.translate(tbl))

[out]:
'CUAG'

Using RNA_compliment使用RNA_compliment

  • str.maketrans accepts one argument as a dictionary str.maketrans接受一个参数作为字典
  • {ord('A'): 'U', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
    • ord() isn't required ord()不是必需的
# dict without ord
RNA_compliment = {'A': 'U', 'T': 'A', 'G': 'C', 'C': 'G'}

tbl2 = i.maketrans(RNA_compliment)

print(my_str.translate(tbl2))

[out]:
'CUAG'

python 2:蟒蛇2:

  • If you want to make a table, use string.maketrans .如果要制作表格,请使用string.maketrans
  • You can only use the ord with a dict for python3 , not for python2 :您只能将orddict用于python3而不能用于python2
In [1]: from string import maketrans

In [2]: i, j = "ATGC", "UACG"

In [3]: tbl = maketrans(i,j)

In [4]: my_str = "GUTC"

In [5]:  my_str.translate(tbl)
Out[5]: 'CUAG'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM