Rushy Panchal
Rushy Panchal

Reputation: 17532

Error with String Slicing?

I am working on a fairly simple program to convert a given non-coding strand of DNA to all of it's counterparts (coding, mRNA, tRNA, and amino acid chain).

I get an IndexError when I try to slice a string though:

mRNA_parts = mRNA.split(' ')
print mRNA_parts,  # using for debugging purposes

for base in mRNA_parts:
    print base # again, for debugging
    partA = base[0]
    partB = base[1]
    partC = base[2]
    my_acid = (amino_acids[partA][partB][partC]) + ' '
    # 'amino_acids' is a 3D (thrice-nested) dictionary with the corresponding parts of mRNA to convert to the amino acid chain.
    # part of the nested dictionary: amino_acids = {'U': {'U': {'U': 'Phe'}}}. This is only one part (out of 64) of it.
    # Thus, if  the mRNA section was 'UUU', the amino acid would be 'Phe '.
    acid_strand += my_acid

This is the error I get:

['GAU', '']
GAU


Traceback (most recent call last):
  File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\DNA to RNA Converter.py", line 83, in <module>
    main()
  File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\DNA to RNA Converter.py", line 3, in main
    convert(non_coding)
  File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\DNA to RNA Converter.py", line 58, in convert
    partA = base[0]
IndexError: string index out of range

How is it unable to do base[0] where base is 'GAU'?

Based off of what it printed, is 'GAU' not a string? It does not have any quotations around it.

Thanks in advance!

Upvotes: 1

Views: 122

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213261

It's not showing the error for GAU, but for the empty string '', that you are having as the second element of your list. Add a test at the start of your loop to ignore that.

Upvotes: 3

Related Questions