Hi, I didn't really know how to word the title, but I was just wondering if it was possible to write a function and make it accessible as if it was any other str function. It was a simple (but useful) few lines which returned a list of all the occurrences of a substring within a string. I'd have to call it by findAll( string, substring ) , but I would like to be able to call it like the built-in find function, i.e. string.findAll( substring ) . Is this possible? Thanks!

Recommended Answers

All 2 Replies

I don't think it's possible. The normal way to do this is to create your own subclass of str like this

class mystr(str):
  def __new__(cls, *args):
    return str.__new__(cls, *args)
  def findAll(self, other):
    print("Couldn't find '%s' in '%s'!" % (other, self))

if __name__ == "__main__":
  s = mystr("Hello world")
  s.findAll("Hi")

It's a good solution because your class will behave much like the str class and can be used in functions which use a str. For example, you can pass a mystr to open, etc...

commented: Great idea to create my own str class! +2

Oh, I didn't think about creating my own str class. That's a great idea and it works wonderfully. Thanks Gribouillis!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.