I want to replace some characters in a string using a pythonic approach.
A -> T
C -> G
G -> C
T -> A
Example:
AAATCGATTGAT
will transform into
TTTAGCTAACTA
What I did:
def swap(string):
string = re.sub('A', 'aux', string)
string = re.sub('T', 'A', string)
string = re.sub('aux', 'T', string)
string = re.sub('C', 'aux', string)
string = re.sub('G', 'C', string)
string = re.sub('aux', 'G', string)
return string
It worked great, but i'm looking for a more pythonic way to reach that.
Use a dictionary with a comprehension and str.join
:
translateDict = {
"A" : "T",
"C" : "G",
"G" : "C",
"T" : "A"
}
s1 = "AAATCGATTGAT"
reconstructed = "".join(translateDict.get(s, s) for s in s1)
Here you have the live example
Note the use of dict.get
; in case the letter is not in the dictionary we just let it as it was.
As @bravosierra99 suggests, you can also simply use str.translate
:
reconstructed = s1.translate(string.maketrans(translateDict))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With