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.
#import the class from the collections module
from collections import UserString
S = UserString('Pynerds')
#use string methods
print(S.upper())
print(S.lower())
#string operations
print(S + "Python")
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
from collections import UserString
class MyString(UserString):
def capitalize_words(self):
return ' '.join([word.capitalize() for word in self.data.split(' ')])
S = MyString('this is a test string')
print(S.capitalize_words())