What is the fastest way to replace certain characters in a given string other than using str.translate()
?
Given a sequence
that only consists of letters "A", "T", "G", and "C", I want to replace each instance of "A" with "T", "T" with "A", "C" with "G", and "G" with "C". To do this, I used an ascii dictionary map = {65:84,84:65,71:67,67:71}
, and do sequence.translate(map)
. However, in Python 3.8
this appears to be slow. I saw people mention using byte
or bytearray
to do this, but I just don't know how to make it work.
It looks like I first need to encode the sequence using sequence.encode('ascii', 'ignore')
and then use translate()
to do the translation?
Can anybody please help me?
For example,
sequence = 'ATGCGTGCGCGACTTT'
# {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
map_dict = {65:84,84:65,71:67,67:71}
# expect 'TACGCACGCGCTGAAA'
sequence.translate(map_dict)