The UserString Module

(New in 2.0) The UserString module contains two classes, UserString and MutableString. The former is a wrapper for the standard string type that can be subclassed, and the latter is a variation that allows you to modify the string in place.

Note that MutableString is not very efficient. Most operations are implemented using slicing and string concatenation. If performance is important, use lists of string fragments or the array module. Example 2-17 shows the UserString module.

Example 2-17. Using the UserString Module

File: userstring-example-1.py

import UserString

class MyString(UserString.MutableString):

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

 def insert(self, index, s):
 self.data = self.data[index:] + s + self.data[index:]

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

file = open("samples/book.txt")
text = file.read()
file.close()

book = MyString(text)

for bird in ["gannet", "robin", "nuthatch"]:
 book.remove(bird)

print book

...
C: The one without the !
P: The one without the -!!! They've ALL got the !! It's a
Standard British Bird, the , it's in all the books!!!
...

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net