Python | Collections Module | UserString | Codecademy

In Python, a UserString is a class in the collections module. It is a custom wrapper for string objects, behaving like a string but allowing easier subclassing. Unlike directly subclassing str, UserString stores its content in the .data attribute.

Note: While UserString behaves like a string and supports the same operations, some methods return a regular str instead of another UserString.

Syntax

myString = collections.UserString(seq)
  • seq: It can be anything that can be converted into a str or iterable of characters, like a list or tuple of individual characters.

Return value:

  • A UserString instance, which is an object that contains the content derived from seq.

Example

The following example demonstrates the usage of the UserString method:

from collections import UserString

myString = 'First example of a UserString!'

customString = UserString(myString)

print(customString.data)

This is the output of the above code:

First example of a UserString!

Codebyte Example

The following example creates a UserString and demonstrates its usage more in detail, along with a subclass that removes vowels: