Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom string type in Python

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?

like image 708
Yotam Vaknin Avatar asked Jan 23 '14 08:01

Yotam Vaknin


People also ask

How do you create your own type in Python?

The short answer is you can't make a new type in python without editing the source code (written in C). However the answer about creating a class in python is probably the easier route to go since editing the source can create compatibility problems with packages (potentially speaking).

How do you build a string in Python?

How to create a string in Python? Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.

What is the __ str __ method in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

How do you add a string to a function in Python?

To append a string to another in Python, use the += operator. Python += operator appends a string to another. It adds two values together and assigns the final value to a variable.


1 Answers

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.

like image 100
user2357112 supports Monica Avatar answered Sep 21 '22 12:09

user2357112 supports Monica