I want to be able to replace certain characters. The desired replacement order should be
A -> U, T -> A, G -> C, C -> G.
But for some reason, C does not get replaced with G. I've linked the code that I have so far.
v = "ATGC"
DNA = [v]
MRNA = []
for s in DNA:
MRNA.append(s.replace('A', 'U').replace('T', 'A').replace('C', 'G').replace('G', 'C'))
print(MRNA)
Using MRNA.replace('C', 'G').replace('G', 'C') will replace any 'C' by a 'G' which is immediately replaced back with a 'C'.
Instead of multiple str.replace you should use a translation table with str.maketrans and str.translate. Since this works in a single pass, it both avoids undoing a replacement and gets more efficient as the number of call to str.replace increases.
def dna_to_rna(s):
trans_table = str.maketrans('ATCG', 'UAGC')
return s.translate(trans_table)
print(dna_to_rna('ACGTAC')) # 'UGCAUG'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With