Skip to content

Python UserString – Custom Python Strings with collections

Python UserString - Custom Python Strings with collections Cover Image

Building custom strings allows you to define powerful programs. You can easily build new strings that have custom behavior or new functionalities, which build on top of regular Python strings. In this tutorial, you’ll learn how to use the Python collections UserDict class to create custom dictionaries. You’ll also learn how to build your own custom string, by building a string with custom methods.

By the end of this tutorial, you’ll have learned the following:

  • How to build custom Python strings using the UserString class
  • How to understand common use cases for the UserString class by building an example custom string

Understanding the Python collections UserString Class

The UserString class has been included in Python since version 1.6, however, it was moved to the collections module in Python 3. We can use the UserString class to inherit from a string to enhance or modify its default behavior. In particular, the class simply subclasses, rather than instantiates.

This means that the class inherits from the string and emulates it. The UserString also makes the original string accessible through a .data attribute.

The class created a data attribute, which stores the contents of the underlying string. This allows you to build custom methods and behavior that have access to the underlying data.

Let’s see how the class is defined and how to create a simple UserString:

# Creating a UserDict
from collections import UserString

class Custom(UserString):
    pass

custom_string = Custom('datagy.io')
print(custom_string)

# Returns:
# datagy.io

In the example above, we created a UserString that doesn’t modify the behavior of the regular string. This example was merely meant to illustrate that the custom string inherits all default behavior from a normal Python string.

Let’s now dive into an example of how to create a custom string using the UserString class.

Creating a Custom String with Python UserString

In our previous example, we created a UserString string which didn’t modify a string’s behavior at all. However, let’s dive into some more advanced use cases. We’ll create a string that has a few extra methods to print characters in different ways. The string will also strip any punctuation from the string by default.

By default, Python strings let you print out the strings in different ways. For example, you can use the .upper() and .lower() methods to print values in uppercase and lowercase. We’ll create a custom string class that let’s you print in alternating case. This means that a string like 'datagy' will be printed as 'dAtAgY'.

Let’s see how we can use the UserString class to create a custom Python string:

# Create a Custom String Class
from collections import UserString
import re

class FunnyString(UserString):
    def __init__(self, sequence):
        self.data = re.sub(r'[^\w\s]', '', sequence)

    def funnify(self):
        funny = ""
        for idx in range(len(self.data)):
            if not idx % 2:
                funny += self.data[idx].upper()
            else:
                funny += self.data[idx].lower()

        print(funny)

text = FunnyString('Hello! Welcome to datagy.io!')

What’s great about the UserString is that it exposes the underlying string using the .data parameter. This allows you to easily modify the string that’s used to instantiate the object. We can then use the .data attribute in the __init__() method.

# Instantiating a String Without Punctuation
from collections import UserString
import re

class FunnyString(UserString):
    def __init__(self, sequence):
        self.data = re.sub(r'[^\w\s]', '', sequence)

In this case, we’re using the __init__() function to take the original string and remove any punctuation from the string. When we then print the string we create, it’ll be printed without any punctuation in it:

# Printing a Custom String
text = FunnyString('Hello! Welcome to datagy.io!')
print(text)

# Returns: Hello Welcome to datagyio

We can see that the string we passed in was modified to remove any punctuation from it. Similarly, we included an additional method, .funnify():

# Adding a Custom Method to Our UserString
from collections import UserString
import re

class FunnyString(UserString):
    ...
    def funnify(self):
        funny = ""
        for idx in range(len(self.data)):
            if not idx % 2:
                funny += self.data[idx].upper()
            else:
                funny += self.data[idx].lower()

        print(funny)

Our method .funnify() loops over each item in the string and either lowercases it or uppercases it using the modulo operator. Let’s call the method and see what it looks like:

# Calling the Custom String Method
text = FunnyString('Hello! Welcome to datagy.io!')
text.funnify()

# Returns: HeLlO WeLcOmE To dAtAgYiO

We can see that the class first removes the punctuation from the string. When we then call the .funnify() method, the string is uppercased in alternating order.

Conclusion

In this tutorial, you learned how to use the UserString class from the Python collections module to create custom Python strings. You can easily build new strings that have custom behavior or new functionalities, which build on top of regular Python strings.

In this tutorial, you learned how to use the Python collections UserString class to create custom strings. You also learned how to follow through with an example of how to create a custom UserString, by creating a string that removes punctuation and provides a custom method to print strings in alternating casing.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *