Michaelbucher
Michaelbucher

Reputation: 1

How do I correct an issue with string indices needed to be integers?

I keep getting the following error:

  File "./translatetest.py", line 32, in <module>
    residue = cdna[codon]
TypeError: string indices must be integers

I am trying to code a script that will output a single amino acid letter for each set of 3 lets when given a series of codons (set of 3 letters). I also need it to break as soon as a STOP codon is received. Below is what I have right now. Help would be appreciated.

import sys

STOP = '*'
genetic_code = {
  'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 
  'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 
  'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 
  'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',                  
  'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 
  'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', 
  'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 
  'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', 
  'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 
  'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', 
  'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 
  'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', 
  'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 
  'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', 
  'TAC':'Y', 'TAT':'Y', 'TAA':STOP, 'TAG':STOP, 
  'TGC':'C', 'TGT':'C', 'TGA':STOP, 'TGG':'W',
}

cdna = sys.argv[1].upper()
cdnLen = 3
cdns = [ cdna[idx:idx+cdnLen] for idx in range(0, len(cdna), cdnLen) ]


prot = ''
for codon in cdns:
    residue = cdna[codon]
    if residue == STOP:
                break
    prot += residue
print(prot)

Upvotes: 0

Views: 59

Answers (2)

PeptideWitch
PeptideWitch

Reputation: 2349

You can condense your protein string to a single line with the following:

prot = ''.join(genetic_code[codon] for codon in cdns).split('STOP')[0]

But this may not be as efficient as checking for a stop and then breaking.

Upvotes: 1

David
David

Reputation: 8298

Your problem is the following line:

residue = cdna[codon]

You should access the genetic_code to map a triplet to amino acid, so changing it to:

residue = genetic_code[codon]

Upvotes: 2

Related Questions