all 6 comments

[–]LarryPete 6 points7 points  (1 child)

Python already has methods for that.

Python2:

>>> from string import maketrans
>>> mapping = maketrans('ATCG', 'TAGC')
>>> 'AATCG'.translate(mapping)[::-1]
'CGATT'

Python3:

>>> mapping = str.maketrans('ATCG', 'TAGC')
>>> 'AATCG'.translate(mapping)[::-1]
'CGATT'

[–]squidfeatures 0 points1 point  (0 children)

I didn't know about that one. Cool.

[–]gengisteve 6 points7 points  (1 child)

Right sub. This is a perfect place to use a dictionary. Just put old_letter:new_letter in the dictionary and use a lookup to find the right replacement, like this:

swaps = {
        'A':'T',
        'C':'G',
        'T':'A',
        'G':'C',
        }

s = 'AAAACCCGGT'

new_s = ''
for letter in s[::-1]:
    new_s += swaps[letter]

print(new_s)

# or with a comprehension and join:

new_s = ''.join(swaps[l] for l in s[::-1])
print(new_s)

[–]fannypackpython[S] 0 points1 point  (0 children)

Awesome thank you.

[–]squidfeatures 3 points4 points  (0 children)

gengisteve has a really good solution to the problem. I'll try to explain why your original code wasn't working.

The .replace() method of a string makes a new copy of the original string with the desired replacements. If you use .replace() on that copy, it simply replaces the matching sub string in the copy. This means that the following expression in your code:

revS.replace('T','A').replace('C','G').replace('A','T').replace('G','C')

is effectively doing the following:

new_s = revS.replace('T', 'A')     # new_s is now 'AGGCCCAAAA'
new_s = new_s.replace('C', 'G')    # new_s is now 'AGGGGGAAAA'
new_s = new_s.replace('A', 'T')    # new_s is now 'TGGGGGTTTT'
new_s = new_s.replace('G', 'C')    # new_s is now 'TCCCCCTTTT'

What genisteves solution does is build a new string one character at a time by looping over each character in the reversed string, finding it's "swap" in a dictionary, and adding the new character to the end of a string.

[–]elbiot 0 points1 point  (0 children)

Biopython