how can you splice a string using a variable with defined indexes in Python?

62 Views Asked by At

I have 2 files, genomic_dna,txt and exons.txt.

The first file contains the genomic DNA sequence of interest and the second file contains the start and stop codons of the exons.

I want to import the two files and splice the exons out of the DNA sequence to then concatenate them together but I am not sure how to splice it.

At first this is what I tried which worked but it did not use the second file:

#read the file containing the genomic dna
file = open("genomic_dna.txt", "r")

#create the file object
contents =  file.read()

#extract the exons from the genomic dna
ex1 = contents[5:58]
ex2 = contents[72:133]
ex3 = contents[190:276]
ex4 = contents[340:398]

#concatenate the exons
DNA_Exons = ex1 + ex2 + ex3 + ex4

#open a new file for the exons
file2 = open("DNA_exons.txt", "w")
#write the exons in the new file
file2.write(DNA_Exons)

Then I tried to use the second file as part of my code but I keep getting an error message;

#read the file containing the genomic dna
file2 = open("exons.txt", "r")

#create the file object
contents =  file.read()
contents2 = file2.read()

#get the exon positions from exons.txt
for line in file2:
        position_list = line.split(",")
        start = position_list[0]
        end = position_list[1]

with open("genomic_dna.txt", "r") as file:
        contents = file.read()
        exon = contents.split(start, end)
        print(str(exon))
TypeError: 'str' object cannot be interpreted as an integer

However the .split() function can only contain integers not a variable, is there a way I can get around this as that keeps throwing an error? I also tried the normal splicing like this:

exon = contents[start:end]
TypeError: slice indices must be integers or None or have an __index__ method

But again, you can only use integer indexes as the error message showed.

0

There are 0 best solutions below