在for循环中替换* args

时间:2020-05-03 18:55:32

标签: python for-loop replace args

目标是使用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”)被替换,而其他对则没有。

发生这种情况的原因可能是什么,我该如何进行这项工作?

2 个答案:

答案 0 :(得分:1)

原因是您要在每个循环中覆盖comp_strand,而不保存结果。但是,即使您修复了该错误,它也仍然无法正常运行,如0x5453comment中所述:

它仍然不会执行您想要的操作,因为您一次只交换一个字符。例如,'atta'将在第一次迭代后变成'tttt',然后在第二次迭代后变成'aaaa'

使用str.translate()str.maketrans()替换为多个替换的更好的解决方案。例如:

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

答案 1 :(得分:0)

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