6

In Python, is there an option to create a custom string class, that could be created by typing something like:

a = b"some string"
a.someCustomMethod()

Just like python has its u"" and r"" strings?

4
  • What are you hoping to accomplish this way? Commented Jan 23, 2014 at 9:02
  • 1
    possible duplicate of Add custom method to string object Commented Jan 23, 2014 at 9:06
  • I'm trying to make using my type of string VERY easy for the users of my library. Commented Jan 23, 2014 at 10:08
  • First I thought this was about typing.NewType, but actually it seems to be about basic OOP in python. Commented Jun 22, 2020 at 20:31

1 Answer 1

7

It's straightforward to write your own string class, but you can't get the construction syntax you want. The closest you can get is

a = MyString("some string")

where MyString is your custom class. I suppose you can alias b = MyString if you want.

Also, note that b"some string" is already the bytestring literal syntax. In Python 2, it just makes a regular string. In Python 3, it makes a bytes object, since regular strings are unicode in Python 3.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can subclass str or UserString to create MyString and gain all the properties you'd expect from a normal string in addition to your new property. See docs.python.org/2.7/library/userdict.html?#module-UserString and stackoverflow.com/a/4699190/1970751

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.