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

python - How do I replace characters in a string using a character map?

Code purpose:

I provide a string and match it with dictionary keys; if the key and string match I print the dictionary values.

Here's the code:

def to_rna(dna_input):
    dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
    rna = []
    for key in dna_rna.iterkeys():
        if key in dna_input:
            rna.append(dna_rna[key])
    print "".join(rna)

to_rna("ACGTGGTCTTAA") #the string input

Problem:

The result should be 'UGCACCAGAAUU' but all I get is 'UGAC'. The problem appears to be that I have duplicate characters in the string and the loop is ignoring this. How do I loop through the dictionary so that it returns the dictionary value as many times as the dict key is found?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could use translate(). Edit: I added the regex to return - for bad entries (seemed like a good idea @jh44tx had):

import string
import re
rna_trans = string.maketrans("ACGTU","UGCA-")
rna_trans = re.sub("[^UGCA]","-",rna_trans)
print "ACGTGGTCTTAA".translate(rna_trans)

Since the mappings are 1:1 you can also create a reverse translate:

rev_rna_trans = string.maketrans("UGCAT","ACGT-")
rev_rna_trans = re.sub("[^ACGT]","-",rna_trans)

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

...