0

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!

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by shadwickman
1

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...

Votes + Comments
Great idea to create my own str class!
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.