Search code examples
pythonfor-loopreplaceargs

replacing *args in a for loop


The goal is to replace all characters within a string using a for loop and replace. My code looks like this:

strand_1 = input("type DNA sequence here: ")
for i in ("a", "t"),("t", "a"),("g", "c"),("c", "g"):
    comp_strand = strand_1.replace(*i)

print(f' the complementary strand is: {comp_strand.upper()}')

The output for using 'agtcagtcagtc' looks like this:

type DNA sequence here: agtcagtcagtc
 the complementary strand is: AGTGAGTGAGTG

For some reason i don't understand, only the last pair ("c", "g") actually gets replaced while the others won't.

What might be the cause for this to happen, and how can i make this work?


Solution

  • The reason is that you're overwriting comp_strand each loop, and not saving the result. However even if you fix that, it still won't work, as 0x5453 explained in a comment:

    it still won't do what you want, because you do the swaps one character at a time. For example, 'atta' would become 'tttt' after the first iteration, and then 'aaaa' after the second.

    The better solution for multiple replacements is str.translate() with str.maketrans(). For example:

    table = str.maketrans('atgc', 'tacg')
    strand = 'agtcagtcagtc'
    complementary = strand.translate(table)
    print(complementary)  # -> tcagtcagtcag