blob: ea3d5155eb943058b868bbe15a2f8e236de35fef [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)
Thomas Wouters104a7bc2000-08-24 20:14:10 +000053 def __iadd__(self, other):
54 if isinstance(other, UserString):
55 self.data += other.data
56 elif isinstance(other, StringType) or isinstance(other, UnicodeType):
57 self.data += other
Peter Schneider-Kampfa12e132000-08-24 21:47:34 +000058 else:
Thomas Wouters104a7bc2000-08-24 20:14:10 +000059 self.data += str(other)
60 return self
Fred Drakea22b5762000-04-03 03:51:50 +000061 def __mul__(self, n):
62 return self.__class__(self.data*n)
63 __rmul__ = __mul__
Thomas Wouters104a7bc2000-08-24 20:14:10 +000064 def __imull__(self, n):
65 self.data += n
66 return self
Fred Drakea22b5762000-04-03 03:51:50 +000067
68 # the following methods are defined in alphabetical order:
69 def capitalize(self): return self.__class__(self.data.capitalize())
70 def center(self, width): return self.__class__(self.data.center(width))
71 def count(self, sub, start=0, end=sys.maxint):
72 return self.data.count(sub, start, end)
73 def encode(self, encoding=None, errors=None): # XXX improve this?
74 if encoding:
75 if errors:
76 return self.__class__(self.data.encode(encoding, errors))
77 else:
78 return self.__class__(self.data.encode(encoding))
79 else:
80 return self.__class__(self.data.encode())
81 def endswith(self, suffix, start=0, end=sys.maxint):
82 return self.data.endswith(suffix, start, end)
83 def expandtabs(self, tabsize=8):
84 return self.__class__(self.data.expandtabs(tabsize))
85 def find(self, sub, start=0, end=sys.maxint):
86 return self.data.find(sub, start, end)
87 def index(self, sub, start=0, end=sys.maxint):
88 return self.data.index(sub, start, end)
Jeremy Hyltonfd547572000-07-10 17:07:17 +000089 def isalpha(self): return self.data.isalpha()
90 def isalnum(self): return self.data.isalnum()
Fred Drakea22b5762000-04-03 03:51:50 +000091 def isdecimal(self): return self.data.isdecimal()
92 def isdigit(self): return self.data.isdigit()
93 def islower(self): return self.data.islower()
94 def isnumeric(self): return self.data.isnumeric()
95 def isspace(self): return self.data.isspace()
96 def istitle(self): return self.data.istitle()
97 def isupper(self): return self.data.isupper()
98 def join(self, seq): return self.data.join(seq)
99 def ljust(self, width): return self.__class__(self.data.ljust(width))
100 def lower(self): return self.__class__(self.data.lower())
101 def lstrip(self): return self.__class__(self.data.lstrip())
102 def replace(self, old, new, maxsplit=-1):
103 return self.__class__(self.data.replace(old, new, maxsplit))
104 def rfind(self, sub, start=0, end=sys.maxint):
105 return self.data.rfind(sub, start, end)
106 def rindex(self, sub, start=0, end=sys.maxint):
107 return self.data.rindex(sub, start, end)
108 def rjust(self, width): return self.__class__(self.data.rjust(width))
109 def rstrip(self): return self.__class__(self.data.rstrip())
110 def split(self, sep=None, maxsplit=-1):
111 return self.data.split(sep, maxsplit)
Guido van Rossum86662912000-04-11 15:38:46 +0000112 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
Fred Drakea22b5762000-04-03 03:51:50 +0000113 def startswith(self, prefix, start=0, end=sys.maxint):
114 return self.data.startswith(prefix, start, end)
115 def strip(self): return self.__class__(self.data.strip())
116 def swapcase(self): return self.__class__(self.data.swapcase())
117 def title(self): return self.__class__(self.data.title())
Fred Drakea8939572000-08-21 21:47:20 +0000118 def translate(self, *args):
119 return self.__class__(self.data.translate(*args))
Fred Drakea22b5762000-04-03 03:51:50 +0000120 def upper(self): return self.__class__(self.data.upper())
121
122class MutableString(UserString):
123 """mutable string objects
124
125 Python strings are immutable objects. This has the advantage, that
126 strings may be used as dictionary keys. If this property isn't needed
127 and you insist on changing string values in place instead, you may cheat
128 and use MutableString.
129
130 But the purpose of this class is an educational one: to prevent
131 people from inventing their own mutable string class derived
132 from UserString and than forget thereby to remove (override) the
133 __hash__ method inherited from ^UserString. This would lead to
134 errors that would be very hard to track down.
135
136 A faster and better solution is to rewrite your program using lists."""
137 def __init__(self, string=""):
138 self.data = string
139 def __hash__(self):
140 raise TypeError, "unhashable type (it is mutable)"
141 def __setitem__(self, index, sub):
142 if index < 0 or index >= len(self.data): raise IndexError
143 self.data = self.data[:index] + sub + self.data[index+1:]
144 def __delitem__(self, index):
145 if index < 0 or index >= len(self.data): raise IndexError
146 self.data = self.data[:index] + self.data[index+1:]
147 def __setslice__(self, start, end, sub):
148 start = max(start, 0); end = max(end, 0)
149 if isinstance(sub, UserString):
150 self.data = self.data[:start]+sub.data+self.data[end:]
151 elif isinstance(sub, StringType) or isinstance(sub, UnicodeType):
152 self.data = self.data[:start]+sub+self.data[end:]
153 else:
154 self.data = self.data[:start]+str(sub)+self.data[end:]
155 def __delslice__(self, start, end):
156 start = max(start, 0); end = max(end, 0)
157 self.data = self.data[:start] + self.data[end:]
158 def immutable(self):
159 return UserString(self.data)
160
161if __name__ == "__main__":
162 # execute the regression test to stdout, if called as a script:
163 import os
164 called_in_dir, called_as = os.path.split(sys.argv[0])
165 called_in_dir = os.path.abspath(called_in_dir)
166 called_as, py = os.path.splitext(called_as)
167 sys.path.append(os.path.join(called_in_dir, 'test'))
168 if '-q' in sys.argv:
169 import test_support
170 test_support.verbose = 0
171 __import__('test_' + called_as.lower())