【问题标题】:is there a way to replace letters once in a string? [duplicate]有没有办法在字符串中替换一次字母? [复制]
【发布时间】:2020-08-22 17:23:50
【问题描述】:

我遇到了一个问题,它要么将所有 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)
  • 我正在做 DNA 到 RNA 的翻译代码!所以 A 替换为 U,G 替换为 C,T 替换为 A,C 替换为 G

【问题讨论】:

标签: python python-3.x bioinformatics biopython


【解决方案1】:

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

a_string = "GAGTCGCGTC"
string1 = "GATC"
string2 = "CUAG"
print(a_string.translate(str.maketrans(string1, string2)))

输出:

CUCAGCGCAG

【讨论】:

    【解决方案2】:

    在 Python 3 中,您可以使用 translate:

    a_string = 'GAGTCGCGTCTACACATGCAGTCGAACGGTAGCACAGAGAGCTTGCTCTCGGGTG' 
    trans = {
        'G': 'C',
        'A': 'U',
        'T': 'A',
        'C': 'G'
    }
    print(a_string.translate(str.maketrans(trans)))
    # CUCAGCGCAGAUGUGUACGUCAGCUUGCCAUCGUGUCUCUCGAACGAGAGCCCAC
    

    【讨论】:

      【解决方案3】:

      您可以替换为小写个字母,然后只有在所有替换完成后,才将字符串完全转为大写。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-12
        • 1970-01-01
        • 2011-06-27
        • 2021-10-27
        • 2020-07-29
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多