Custom Python Strings: Inheriting From str vs UserString
The Python str
class has many useful features that can help you out when you’re processing text or strings in your code. However, in some situations, all these great features may not be enough for you. You may need to create custom string-like classes. To do this in Python, you can inherit from the built-in str
class directly or subclass UserString
, which lives in the collections
module.
In this tutorial, you’ll learn how to:
- Create custom string-like classes by inheriting from the built-in
str
class - Build custom string-like classes by subclassing
UserString
from thecollections
module - Decide when to use
str
orUserString
to create custom string-like classes
Meanwhile, you’ll write a few examples that’ll help you decide whether