Python collections.UserString

The class UserString in Python acts as a wrapper around a string object. This class is useful when one wants to create a string of their own with some modified functionality.

In other words, it can be considered as a way of adding new behaviours for the string. This class takes any argument that can be converted to a string. So, the string is accessible by the data attribute of this class.

Syntax :

The signature for the UserString is as shown below.

collections.UserString(sequence)

Python UserString Examples:

Example 1: In this example, we will create a UserString using the existing number. In this case, the number gets converted to a string and is now available as an attribute.

#Importing UserString 
from collections import UserString 
#Initializing
data = 123
 
ud = UserString(data) 
#It concats string and prints it twice
print(ud.data + ud.data)

Output

123123

Example 2: In this case, we will create a UserString wherein it acts as a wrapper class for a customized string object. Thus, it will let us append and replace the characters in a string.

#Importing UserString 
from collections import UserString  
 
# Defining a class
class Stringeg(UserString):
     
    def append(self, s):
        self.data += s
         
    def rep(self, s):
        self.data = self.data.replace(s, "*")
     
s = Stringeg("python")
print("Original String:", s.data)
 
# Calling append
s.append("s")
print("String after append:", s.data)
 
# Replace one character with other
s.rep("o")
print("String after replace:", s.data)

Output

Original String: python
String after append: pythons
String after replace: pyth*ns

Example 3: In this case, we will create a UserString wherein it acts as a wrapper class for a customized string object. Thus, it will let us remove the characters from a string.

#Importing UserString 
from collections import UserString
#Defining class  
class stringdemo(UserString):

    def append(self, a):
        self.data = self.data + a

    def remove(self, s):
        self.data = self.data.replace(s, "")

states='delhi maharashtra gujarat madhyapradesh tamilnadu kerala goa pune'
s = stringdemo(states)

for i in ['mumbai','pune']:
    s.remove(i)

print(s)

Output

delhi maharashtra gujarat madhyapradesh tamilnadu kerala goa 

References

Happy Learning 🙂