-1

I'm running into a problem where it either replaces all Gs to Cs but doesn't replace the C to Gs, what can I do to fix this problem? the output im getting right now is "GUGAGGGGAG" the output im looking for is "CUCAGCGCAG" This is the code that I have till now:

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)
  • I'm doing a DNA to RNA translation code! so A replaces to U, G to C, T to A and C to G
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ragster
  • 17
  • 3

3 Answers3

5

Using str.translate we can change the whole string in one go:

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

Output:

CUCAGCGCAG
Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20
2

In Python 3 you can use translate:

a_string = 'GAGTCGCGTCTACACATGCAGTCGAACGGTAGCACAGAGAGCTTGCTCTCGGGTG' 
trans = {
    'G': 'C',
    'A': 'U',
    'T': 'A',
    'C': 'G'
}
print(a_string.translate(str.maketrans(trans)))
# CUCAGCGCAGAUGUGUACGUCAGCUUGCCAUCGUGUCUCUCGAACGAGAGCCCAC
M. Abreu
  • 366
  • 2
  • 5
1

You can perform the replacement to lowercase letters, and then only when all replacements have been done, turn the string completely to uppercase.

trincot
  • 317,000
  • 35
  • 244
  • 286