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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Yotam Vaknin
  • 676
  • 4
  • 19

1 Answers1

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    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 http://docs.python.org/2.7/library/userdict.html?#module-UserString and http://stackoverflow.com/a/4699190/1970751 – Cilyan Jan 23 '14 at 09:43