IndexError: string index out of range?
<p>I keep getting an <code>IndexError: string index out of range</code> exception on the following code and I cannot figure out why.</p>

<p>I am supposed to solve the following problem recursively.</p>

<blockquote>
  <p>Finally, write <code>transcribe( S )</code>. Here is its description:</p>
  
  <p>In an incredible molecular feat called transcription, your cells create molecules of messenger RNA that mirror the sequence of nucleotides in your DNA. The RNA is then used to create proteins that do the work of the cell. Write a recursive function <code>transcribe( S )</code>, which should take as input a string <code>S</code>, which will have DNA nucleotides (capital letter As, Cs, Gs, and Ts). There may be other characters, too, though they will be ignored by your transcribe functionâthese might be spaces or other characters that are not really DNA nucleotides.</p>
  
  <p>Then, transcribe should return as output the messenger RNA that would be produced from that string S. The correct output simply uses replacement:</p>
  
  <p>As in the input become Us in the output.<br>
  Cs in the input become Gs in the output.<br>
  Gs in the input become Cs in the output.<br>
  Ts in the input become As in the output.<br>
  any other input characters should disappear from the output altogether</p>
</blockquote>

<pre><code>def transcribe( S ):
  tran = '' * len(S)
  if S[0] == 'A':
    tran = tran + 'U' + transcribe( S[1:] )
    return tran
  elif S[0] == 'C':
    tran = tran + 'G' + transcribe( S[1:] )
    return tran
  elif S[0] == 'G':
    tran = tran + 'C' + transcribe( S[1:] )
    return tran
  elif S[0] == 'T':
    tran = tran + 'A' + transcribe( S[1:] )
    return tran
  else:
    return ""

print transcribe('GATTACA')
</code></pre>

<p>Trying to index with <code>[0]</code> into an <em>empty string</em> raises an <code>IndexError</code>.</p>

<p>You need to test if the string is empty <em>first</em>, as eventually <code>S[1:]</code> will pass an empty sting into <code>transcribe()</code>:</p>

<pre><code>if not S:
    return ''
</code></pre>

<p>You should drop the <code>tran</code> string altogether; that is <em>always</em> an empty string. <code>'' * &lt;any number&gt;</code> is still <code>''</code>.</p>

<p>Rather than test each possible letter in a separate <code>if</code> statement, use a dictionary to map one character to another:</p>

<pre><code>mapping = {'A': 'U', 'C': 'G', 'G': 'C', 'T': 'A'}
def transcribe(S):
    if not S:
        return ''
    replacement = mapping.get(S[0], '')  # default is empty
    return replacement + transcribe(S[1:])
</code></pre>

python python-2.7