Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

How to do it...

  1. userstring_import.py is simple in that it shows how to create a method to append a sequence to a string, much like adding more items to a list:
      >>> from collections import UserString      >>> class AppendString(UserString):      ...     def append(self, s):      ...         self.data = self.data + s      ...       >>> s = AppendString("abracadabra")      >>> s.append("spam and bananas")      >>> print(s)      abracadabraspam and bananas      >>> l = "banana"       # show that regular strings don't have an append method      >>> l.append("apple")      Traceback (most recent call last):          File "<stdin>", line 1, in <module>      AttributeError: 'str' object has no attribute 'append'
    • The first step, as always, is to import the UserString class from the collections module.
    • Next, a simple subclass of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content