Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters by chaining str.replace methods produces wrong result

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)
like image 830
Jakob Nielsen Avatar asked Oct 23 '25 11:10

Jakob Nielsen


1 Answers

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'
like image 104
Olivier Melançon Avatar answered Oct 26 '25 00:10

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!