0

I have used the following code to handle this task:

dna = input('Enter:')
b = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
for x,y in b.items():
    dna = dna.replace(x,y)
print(dna)

However, it seems to be replacing only T and G, ignoring A and C. Can you please explain why it happens and how should I avoid this issue. Still pretty new to Python. Thank you in advance!

Seva
  • 11
  • 1
  • You basically have the same problem as [this user](https://stackoverflow.com/questions/46535603/how-can-i-replace-multiple-characters-in-a-string-using-python). – Aran-Fey Sep 08 '18 at 19:05
  • First you turn A to T, but then you turn T to A, which includes the previously replaced original A. – user2390182 Sep 08 '18 at 19:22

1 Answers1

0

You can do the following:

dna = input('Enter:')
b = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}

dna = ''.join(b[x] for x in dna)
# or more robustly, ignoring unknown characters
# dna = ''.join(b.get(x, x) for x in dna)

This will rebuild the entire string in one iteration which avoids the back-and-forth replacements of your initial approach.

user2390182
  • 72,016
  • 6
  • 67
  • 89