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
566 views
in Technique[技术] by (71.8m points)

python - DNA to RNA using str.translate()

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

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:

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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'

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:

  • 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'

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

...