blob: 070b3e1fd1dcc50713a3b12a4ffcc5c9f15553a4 [file] [log] [blame]
Fred Drakea22b5762000-04-03 03:51:50 +00001#!/usr/bin/env python
2## vim:ts=4:et:nowrap
3"""A user-defined wrapper around string objects
4
5Note: string objects have grown methods in Python 1.6
6This module requires Python 1.6 or later.
7"""
8from types import StringType, UnicodeType
9import sys
10
11class UserString:
12 def __init__(self, seq):
13 if isinstance(seq, StringType) or isinstance(seq, UnicodeType):
14 self.data = seq
15 elif isinstance(seq, UserString):
16 self.data = seq.data[:]
17 else:
18 self.data = str(seq)
19 def __str__(self): return str(self.data)
20 def __repr__(self): return repr(self.data)
21 def __int__(self): return int(self.data)
22 def __long__(self): return long(self.data)
23 def __float__(self): return float(self.data)
24 def __complex__(self): return complex(self.data)
25 def __hash__(self): return hash(self.data)
26
27 def __cmp__(self, string):
28 if isinstance(string, UserString):
29 return cmp(self.data, string.data)
30 else:
31 return cmp(self.data, string)
32 def __contains__(self, char):
33 return char in self.data
34
35 def __len__(self): return len(self.data)
36 def __getitem__(self, index): return self.__class__(self.data[index])
37 def __getslice__(self, start, end):
38 start = max(start, 0); end = max(end, 0)
39 return self.__class__(self.data[start:end])
40
41 def __add__(self, other):
42 if isinstance(other, UserString):
43 return self.__class__(self.data + other.data)
44 elif isinstance(other, StringType) or isinstance(other, UnicodeType):
45 return self.__class__(self.data + other)
46 else:
47 return self.__class__(self.data + str(other))
48 def __radd__(self, other):
49 if isinstance(other, StringType) or isinstance(other, UnicodeType):
50 return self.__class__(other + self.data)
51 else:
52 return self.__class__(str(other) + self.data)
53 def __mul__(self, n):
54 return self.__class__(self.data*n)
55 __rmul__ = __mul__
56
57 # the following methods are defined in alphabetical order:
58 def capitalize(self): return self.__class__(self.data.capitalize())
59 def center(self, width): return self.__class__(self.data.center(width))
60 def count(self, sub, start=0, end=sys.maxint):
61 return self.data.count(sub, start, end)
62 def encode(self, encoding=None, errors=None): # XXX improve this?
63 if encoding:
64 if errors:
65 return self.__class__(self.data.encode(encoding, errors))
66 else:
67 return self.__class__(self.data.encode(encoding))
68 else:
69 return self.__class__(self.data.encode())
70 def endswith(self, suffix, start=0, end=sys.maxint):
71 return self.data.endswith(suffix, start, end)
72 def expandtabs(self, tabsize=8):
73 return self.__class__(self.data.expandtabs(tabsize))
74 def find(self, sub, start=0, end=sys.maxint):
75 return self.data.find(sub, start, end)
76 def index(self, sub, start=0, end=sys.maxint):
77 return self.data.index(sub, start, end)
Jeremy Hyltonfd547572000-07-10 17:07:17 +000078 def isalpha(self): return self.data.isalpha()
79 def isalnum(self): return self.data.isalnum()
Fred Drakea22b5762000-04-03 03:51:50 +000080 def isdecimal(self): return self.data.isdecimal()
81 def isdigit(self): return self.data.isdigit()
82 def islower(self): return self.data.islower()
83 def isnumeric(self): return self.data.isnumeric()
84 def isspace(self): return self.data.isspace()
85 def istitle(self): return self.data.istitle()
86 def isupper(self): return self.data.isupper()
87 def join(self, seq): return self.data.join(seq)
88 def ljust(self, width): return self.__class__(self.data.ljust(width))
89 def lower(self): return self.__class__(self.data.lower())
90 def lstrip(self): return self.__class__(self.data.lstrip())
91 def replace(self, old, new, maxsplit=-1):
92 return self.__class__(self.data.replace(old, new, maxsplit))
93 def rfind(self, sub, start=0, end=sys.maxint):
94 return self.data.rfind(sub, start, end)
95 def rindex(self, sub, start=0, end=sys.maxint):
96 return self.data.rindex(sub, start, end)
97 def rjust(self, width): return self.__class__(self.data.rjust(width))
98 def rstrip(self): return self.__class__(self.data.rstrip())
99 def split(self, sep=None, maxsplit=-1):
100 return self.data.split(sep, maxsplit)
Guido van Rossum86662912000-04-11 15:38:46 +0000101 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
Fred Drakea22b5762000-04-03 03:51:50 +0000102 def startswith(self, prefix, start=0, end=sys.maxint):
103 return self.data.startswith(prefix, start, end)
104 def strip(self): return self.__class__(self.data.strip())
105 def swapcase(self): return self.__class__(self.data.swapcase())
106 def title(self): return self.__class__(self.data.title())
Fred Drakea8939572000-08-21 21:47:20 +0000107 def translate(self, *args):
108 return self.__class__(self.data.translate(*args))
Fred Drakea22b5762000-04-03 03:51:50 +0000109 def upper(self): return self.__class__(self.data.upper())
110
111class MutableString(UserString):
112 """mutable string objects
113
114 Python strings are immutable objects. This has the advantage, that
115 strings may be used as dictionary keys. If this property isn't needed
116 and you insist on changing string values in place instead, you may cheat
117 and use MutableString.
118
119 But the purpose of this class is an educational one: to prevent
120 people from inventing their own mutable string class derived
121 from UserString and than forget thereby to remove (override) the
122 __hash__ method inherited from ^UserString. This would lead to
123 errors that would be very hard to track down.
124
125 A faster and better solution is to rewrite your program using lists."""
126 def __init__(self, string=""):
127 self.data = string
128 def __hash__(self):
129 raise TypeError, "unhashable type (it is mutable)"
130 def __setitem__(self, index, sub):
131 if index < 0 or index >= len(self.data): raise IndexError
132 self.data = self.data[:index] + sub + self.data[index+1:]
133 def __delitem__(self, index):
134 if index < 0 or index >= len(self.data): raise IndexError
135 self.data = self.data[:index] + self.data[index+1:]
136 def __setslice__(self, start, end, sub):
137 start = max(start, 0); end = max(end, 0)
138 if isinstance(sub, UserString):
139 self.data = self.data[:start]+sub.data+self.data[end:]
140 elif isinstance(sub, StringType) or isinstance(sub, UnicodeType):
141 self.data = self.data[:start]+sub+self.data[end:]
142 else:
143 self.data = self.data[:start]+str(sub)+self.data[end:]
144 def __delslice__(self, start, end):
145 start = max(start, 0); end = max(end, 0)
146 self.data = self.data[:start] + self.data[end:]
147 def immutable(self):
148 return UserString(self.data)
149
150if __name__ == "__main__":
151 # execute the regression test to stdout, if called as a script:
152 import os
153 called_in_dir, called_as = os.path.split(sys.argv[0])
154 called_in_dir = os.path.abspath(called_in_dir)
155 called_as, py = os.path.splitext(called_as)
156 sys.path.append(os.path.join(called_in_dir, 'test'))
157 if '-q' in sys.argv:
158 import test_support
159 test_support.verbose = 0
160 __import__('test_' + called_as.lower())