使用str.translate()从DNA到RNA [英] DNA to RNA using str.translate()

查看:89
本文介绍了使用str.translate()从DNA到RNA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python将DNA代码转换为RNA代码...

I'm trying to convert the DNA code into RNA code using Python...

我这样写:

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

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

它有效,但是..现在我需要将 A转换为U T转换为A G转换为C C到G ...,我研究了如何做到这一点,并且做到了:

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:

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)

但是我得到这个错误:

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

我做错了什么?

推荐答案

python 3:

  • str.maketrans 是静态方法,该方法返回可用于 str.translate() 的转换表.
  • 如果有两个参数,则它们必须是长度相等的字符串.
  • python 3:

    • str.maketrans is a static method, which returns a translation table usable for 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'
      

      使用RNA_compliment

      • str.maketrans接受一个参数作为字典
      • {ord('A'): 'U', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
          不需要
        • ord()
        • Using RNA_compliment

          • str.maketrans accepts one argument as a dictionary
          • {ord('A'): 'U', ord('T'): 'A', ord('G'): 'C', ord('C'): 'G'}
            • ord() isn't required
            • # 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:

              • 如果要创建表,请使用 string.maketrans .
              • 对于 python3 ,您只能将orddict一起使用,对于 python2 不能:
              • python 2:

                • If you want to make a table, use string.maketrans.
                • You can only use the ord with a dict for python3, not for 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'
                  

                  这篇关于使用str.translate()从DNA到RNA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆