有没有办法在字符串中替换一次字母?

Rag*_*ter -2 python bioinformatics biopython python-3.x

我遇到了一个问题,它要么将所有 Gs 替换为 Cs,但不将 C 替换为 Gs,我该怎么做才能解决这个问题?我现在得到的输出是“GUGAGGGGAG”我正在寻找的输出是“CUCAGCGCAG”这是我到目前为止的代码:

a_string = "GAGTCGCGTC" 
remove_characters = ["G", "A", "T", "C"]
ch1 = "G"
ch2 = "A"
ch3 = "T"
ch4 = "C"
a_string = a_string.replace (ch1, "C")
a_string = a_string.replace (ch2, "U")
a_string = a_string.replace (ch3, "A")
a_string = a_string.replace (ch4, "G")
print (a_string)
Run Code Online (Sandbox Code Playgroud)
  • 我正在做 DNA 到 RNA 的翻译代码!所以A替换为U,G替换为C,T替换为A,C替换为G

Ham*_*son 5

使用str.translate我们可以一次性更改整个字符串:

a_string = "GAGTCGCGTC"
string1 = "GATC"
string2 = "CUAG"
print(a_string.translate(str.maketrans(string1, string2)))
Run Code Online (Sandbox Code Playgroud)

输出:

CUCAGCGCAG
Run Code Online (Sandbox Code Playgroud)