This is a case where you might consider using a function because it's more portable and reusable in later parts of code. Here is a simple solution to your problem:
def geneSwap(c):
return {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
}[c]
s = str(raw_input("Enter a string: "))
reversed = s[::-1]
[geneSwap(c) for c in reversed]
print reversed
However, Python's list processing capabilities allow for much more condensed coding. This uses the geneSwap()
function and reverses the sequence all in one line (shiny!):
def geneSwap(c):
return {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
}[c]
s = str(raw_input("Enter a string: "))
print ''.join( [geneSwap(c) for c in s[::-1]] )
** Thanks @BrianO for the correction on the print line.
For those unfamiliar with the code in the print statement in the second code block, the list operation can be broken down into steps from right to left:
s
is a string which can be treated as a list of characters. So the list operation [::-1]
returns an iterator which increments through the list by increments of -1 from (but not including) the beginning to the beginning (or, from the end to the beginning in reverse order)
[geneSwap(c) for c in s[::-1]]
(or you could replace s[::-1]
for any list) executes the function on every element c
in the list and returns it as a list.
- The last part is a
''.join()
. You'll notice that step 2 results in a list - not a string. Since the OP wants a string, the last step is to compose a string from the list characters. This is done using the join()
string function which joins elements of the passed list using the string the join()
is used on. In this case, the OP wants the characters strung together with nothing separating them. So an empty string is used. If the OP wanted spaces or dashes (-) they would use ' '.join()
or '-'.join()
respectively.
Inspired by Call int() function on every list element?