The UserString
class defined in the collections
module is used when we want to create custom strings. The class is a subclass of the builtin str
type meaning that it inherits the functionality of standard strings
including methods and properties. We use this class as a base class when we want to create our own string-like objects which can have extra or extended features.
It is possible to instantiate UserString
objects directly, however, the instances will behave just like regular strings.
Create custom strings using UserString class
We can create custom strings by subclassing the UserString
class and defining the relevant methods. The following example defines the MyString
class, which adds a custom method 'capitalize_words'
to the string objects