using .replace to replace more than one character in python [duplicate]

走远了吗. 提交于 2021-02-05 11:18:31

问题


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'),phrase.replace('T','A'),phrase.replace('C','G'),phrase.replace('G','C')
    return newphrase

So basically, if I give the string 'TATCGTTAATTCGAT', the desired output would be 'AUAGCAAUUAAGCUA'

instead, I get ('TUTCGTTUUTTCGUT', 'AAACGAAAAAACGAA', 'TATGGTTAATTGGAT', 'TATCCTTAATTCCAT'), which is the phrase I entered but instead of adding the changes all into one phrase, it prints four different translations all with only one character being changes in each translation.

How would I change the code so the newphrase is translated so it is on consecutive string with the desired output instead of having four different phrases?

Thanks for the help


回答1:


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)



回答2:


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

s = 'TATCGTTAATTCGAT'

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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/41838450/using-replace-to-replace-more-than-one-character-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!