Simultaneous .replace functionality

[亡魂溺海] 提交于 2019-11-29 10:31:26

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'

You can use a mapping dictionary:

In [1]: dic={"A":"U","U":"A","G":"C","C":"G"}

In [2]: strs="AUUUGCGGCAAA"

In [3]: "".join(dic[x] for x in strs)
Out[3]: 'UAAACGCCGUUU'

If you're not already using it, I suggest trying out Biopython. It has all sorts of functions for dealing with biological data, including a pretty cool Seq object. There is a reverse_complement() function that does exactly what you're trying to do, and a bunch more that you might not even have thought of yet. Check it out, it's a real time-saver.

>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> my_dna = Seq("AGTACACTGGT", generic_dna)
>>> my_dna
Seq('AGTACACTGGT', DNAAlphabet())
>>> my_dna.complement()
Seq('TCATGTGACCA', DNAAlphabet())
>>> my_dna.reverse_complement()
Seq('ACCAGTGTACT', DNAAlphabet())

I have a simple solution:

# get the sequence from the user:

dna_seq = input("Please enter your sequence here: ")

# make a for loop to read the seq one nucleotide at a time and add each one in a new variable

compliment = ""

for n in dna_seq:

    if n == "A":
        compliment = compliment + "T"
    elif n == "T":
        compliment = compliment + "A"
    elif n == "G":
        compliment = compliment + "C"
    elif n == "C":
        compliment = compliment + "G"

print(compliment)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!