Skip to content Skip to sidebar Skip to footer

Using .replace To Replace More Than One Character In Python

so I am trying to make a simple program that will decode one phrase into a different one. This is the code I have now def mRNA_decode(phrase): newphrase = phrase.replace('A','U

Solution 1:

You can use str.translate() with a translate table:

s = 'TATCGTTAATTCGAT'

s.translate(str.maketrans("ATCG", "UAGC"))
# 'AUAGCAAUUAAGCUA'

Solution 2:

So as an fyi, remember the order is important. For example, if you need to swap characters c and a in the string cat, you can't replace c with a then a with c. Otherwise you'd get these steps:

cat --> aat --> cct

Solution 3:

Simply

def mRNA_decode(phrase):
    newphrase = phrase.replace('A','U').replace('T','A').replace('C','G').replace('G','C')
    return newphrase

Since str is immutable, replace returns new string all the time, and you just need to call next replace method on newly create string.

In your question, you make four independent operations on same string, so they produce four new string per each call. You listed them separated by comma, which is interpreted by Python as tuple declaration.

UPD: as mentioned in comments, instead of few replace call you can call phrase.translate(). You can find an example in other answers.

Solution 4:

it's because you are replacing every time with your phrase variable , the value of phrase doesn't change , so you have 4 different outputs

an advice , using translate function instead :

from string import maketrans
intab = "ATCG"
outtab = "UAGC"
trantab = maketrans(intab, outtab)
phrase.translate(trantab)

Post a Comment for "Using .replace To Replace More Than One Character In Python"