如何使用字符映射表替换字符串中的字符? [英] How do I replace characters in a string using a character map?
问题描述
我提供了一个字符串,并将其与字典键匹配;如果键和字符串匹配,我将打印字典值.
I provide a string and match it with dictionary keys; if the key and string match I print the dictionary values.
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
问题:
结果应该是" UGCACCAGAAUU ",但我得到的只是" UGAC ".问题似乎是我在字符串中有重复的字符,循环忽略了这一点.如何遍历字典,以便它与找到dict键一样多次返回字典值?
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?
推荐答案
如果要为dna_input
中的每个字符输出一个字符,则需要遍历dna_input
中的字符.请注意,get()
函数为不在词典中的字符提供默认设置.我什么也没替换,如果需要的话,您可以在此处放置n
或X.
If you want to output a character for every character in dna_input
you need to iterate over character in dna_input
. Note that the get()
function provides a default for characters that aren't in your dictionary. I am replacing with nothing, if desired you could put an n
here, or an X.
rna.append(dna_rna.get(char, 'n'))
您的代码仅迭代dna_rna
词典中的4个条目.
Your code was only iterating over the 4 entries in the dna_rna
dictionary.
def to_rna(dna_input):
dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
rna = []
for char in dna_input:
rna.append(dna_rna.get(char, ''))
print "".join(rna)
to_rna("ACGTGGTCTTAA") #the string input
但是,这不是翻译字符串的最有效方法.
However, this isn't the most efficient way to translate a string.
这篇关于如何使用字符映射表替换字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!