Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to replace chars

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.

like image 503
lmalmeida Avatar asked Mar 05 '23 10:03

lmalmeida


1 Answers

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))
like image 123
Netwave Avatar answered Mar 16 '23 10:03

Netwave