Python collections.UserString



The Python UserString is present in collections module. This class acts as a wrapper class to the string. It is useful to create a string of our own. We can inherit this class and override its methods, we can also add new method to the class. It can be considered as a way of adding new behaviors for the string.

The UserString class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.

Syntax

Following is the syntax of the Python UserString

collections.UserString(data)

Parameters

It can accept any data type as a parameter.

Return Value

It returns <collections.UserString> class.

Example

Following is an basic example of the Python UserString class −

from collections import UserString
data1 = [1,2,3,4]
# Creating an UserDict
user_str = UserString(data1)
print(user_str)
print("type :", type(user_str))

Following is the output of the above code −

[1, 2, 3, 4]
type : <class 'collections.UserString'>

Inheriting UserString

We can inherit the properties of UserString and can create our own string by changing the functionality of the existing method and can also add new methods to the class.

Example

Following is an example −

from collections import UserString
# Creating a Mutable String
class My_string(UserString):

   # Function to append to
   # string
   def append(self, s):
   	self.data += s
   	
   # Function to remove from 
   # string
   def remove(self, s):
   	self.data = self.data.replace(s, "")
	
str1 = My_string("Welcome ")
print("Original String:", str1.data)

# Appending to string
str1.append("To Tutorialspoint")
print("String After Appending:", str1.data)

# Removing from string
str1.remove("Welcome To")
print("String after Removing:", str1.data)

Following is the output of the above code −

Original String: Welcome 
String After Appending: Welcome To Tutorialspoint
String after Removing:  Tutorialspoint
python_modules.htm
Advertisements