在 for 循环中替换 *args

replacing *args in a for loop

目标是使用 for 循环和 replace 替换字符串中的所有字符。 我的代码如下所示:

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()}')

使用 'agtcagtcagtc' 的输出如下所示:

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

出于某种原因我不明白,实际上只有最后一对("c"、"g")被替换,而其他的不会。

发生这种情况的原因可能是什么,我该如何解决?

@0x5453解释了为什么代码被破坏了,我建议如何修复它:

strand_1 = input("type DNA sequence here: ")
comp_strand = strand1.translate(str.maketrans('atcg', 'tagc'))
print(f' the complementary strand is: {comp_strand.upper()}')

原因是您要覆盖 comp_strand 每个循环,而不是保存结果。但是,即使您修复了它,它仍然无法正常工作,因为 0x5453 explained in a :

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.

多次替换的更好解决方案是str.translate() with str.maketrans()。例如:

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