user3504701
user3504701

Reputation: 45

Error in my Python Code for DNA Sequencing

So here's a code I've been working on. I'm trying to use the str.index method for a given DNA strand, but to no avail. There's an error somewhere in this code, but I'm not sure what I had forgotten to include. If you could give me some pointers as to why this program isn't working, that would be great:

class dnaString (str):
    def __new__(self,s):
        return str.__new__(self,s.upper())

    def getNewStrand (self):
        return str.index("ACTG")

    def printNewStrand (self):
        print ("New DNA strand: {0}".format(str.index("ACTG")))

dna = input("Enter a dna sequence: ")
x=dnaString(dna)
x.printNewStrand()

Upvotes: 0

Views: 217

Answers (1)

unutbu
unutbu

Reputation: 879421

Use self.index, not str.index:

    print ("New DNA strand: {0}".format(self.index("ACTG")))

or better yet, fix getNewStrand and use it in printNewStrand:

def getNewStrand(self):
    return self.index("ACTG")

def printNewStrand(self):
    print("New DNA strand: {0}".format(self.getNewStrand()))

str.index is a method which requires 2 arguments:

>>> str.index('abc','b')
1

It finds the index of the first occurrence of b in abc (if there is one).

self is an instance of str. When you call a method using an instance, the instance is supplied implicitly as the first argument to the function. So self.index('ACTG') calls

str.index(self, 'ACTG')

self.index('ACTG') will raise a ValueError if ACTG is not in self. If you'd rather not raise an error, you could instead call self.find('ACTG'). If ACTG is not in self, self.find will return -1 instead of raising a ValueError. Otherwise, it behaves the same as self.index.

Upvotes: 1

Related Questions