字符串切片出错?

时间:2012-12-22 17:17:41

标签: python string split

我正在研究一个相当简单的程序,将给定的非编码DNA链转换为所有相应的DNA(编码,mRNA,tRNA和氨基酸链)。

当我尝试切片时,我得到IndexError

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

这是我得到的错误:

  
    
      

    
  
['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

如果基地为'GAU',base[0]怎么办?

根据它打印的内容,'GAU'不是字符串?它周围没有任何引用。

提前致谢!

1 个答案:

答案 0 :(得分:3)

它没有显示GAU的错误,但是对于空字符串'',您将其作为列表的第二个元素。在循环开始时添加测试以忽略它。