blob: 4ef22657601897b58ae6cc137a66497f2aa01b10 [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
Tim Peterse1190062001-01-15 03:34:38 +00005Note: string objects have grown methods in Python 1.6
Fred Drakea22b5762000-04-03 03:51:50 +00006This module requires Python 1.6 or later.
7"""
Fred Drakea22b5762000-04-03 03:51:50 +00008import sys
Raymond Hettinger882a4162008-02-07 03:25:46 +00009import collections
Fred Drakea22b5762000-04-03 03:51:50 +000010
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000011__all__ = ["UserString","MutableString"]
12
Raymond Hettinger882a4162008-02-07 03:25:46 +000013class UserString(collections.Sequence):
Fred Drakea22b5762000-04-03 03:51:50 +000014 def __init__(self, seq):
Neal Norwitz418b97e2006-06-12 02:07:24 +000015 if isinstance(seq, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000016 self.data = seq
17 elif isinstance(seq, UserString):
18 self.data = seq.data[:]
Tim Peterse1190062001-01-15 03:34:38 +000019 else:
Fred Drakea22b5762000-04-03 03:51:50 +000020 self.data = str(seq)
21 def __str__(self): return str(self.data)
22 def __repr__(self): return repr(self.data)
23 def __int__(self): return int(self.data)
24 def __long__(self): return long(self.data)
25 def __float__(self): return float(self.data)
26 def __complex__(self): return complex(self.data)
27 def __hash__(self): return hash(self.data)
28
29 def __cmp__(self, string):
30 if isinstance(string, UserString):
31 return cmp(self.data, string.data)
32 else:
33 return cmp(self.data, string)
34 def __contains__(self, char):
35 return char in self.data
36
37 def __len__(self): return len(self.data)
38 def __getitem__(self, index): return self.__class__(self.data[index])
39 def __getslice__(self, start, end):
40 start = max(start, 0); end = max(end, 0)
41 return self.__class__(self.data[start:end])
42
43 def __add__(self, other):
44 if isinstance(other, UserString):
45 return self.__class__(self.data + other.data)
Neal Norwitz418b97e2006-06-12 02:07:24 +000046 elif isinstance(other, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000047 return self.__class__(self.data + other)
48 else:
49 return self.__class__(self.data + str(other))
50 def __radd__(self, other):
Neal Norwitz418b97e2006-06-12 02:07:24 +000051 if isinstance(other, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000052 return self.__class__(other + self.data)
53 else:
54 return self.__class__(str(other) + self.data)
55 def __mul__(self, n):
56 return self.__class__(self.data*n)
57 __rmul__ = __mul__
Neil Schemenauerfe4f7692002-11-18 16:12:54 +000058 def __mod__(self, args):
59 return self.__class__(self.data % args)
Fred Drakea22b5762000-04-03 03:51:50 +000060
61 # the following methods are defined in alphabetical order:
62 def capitalize(self): return self.__class__(self.data.capitalize())
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000063 def center(self, width, *args):
64 return self.__class__(self.data.center(width, *args))
Fred Drakea22b5762000-04-03 03:51:50 +000065 def count(self, sub, start=0, end=sys.maxint):
66 return self.data.count(sub, start, end)
Marc-André Lemburg2d920412001-05-15 12:00:02 +000067 def decode(self, encoding=None, errors=None): # XXX improve this?
68 if encoding:
69 if errors:
70 return self.__class__(self.data.decode(encoding, errors))
71 else:
72 return self.__class__(self.data.decode(encoding))
73 else:
74 return self.__class__(self.data.decode())
Fred Drakea22b5762000-04-03 03:51:50 +000075 def encode(self, encoding=None, errors=None): # XXX improve this?
76 if encoding:
77 if errors:
78 return self.__class__(self.data.encode(encoding, errors))
79 else:
80 return self.__class__(self.data.encode(encoding))
Tim Peterse1190062001-01-15 03:34:38 +000081 else:
Fred Drakea22b5762000-04-03 03:51:50 +000082 return self.__class__(self.data.encode())
83 def endswith(self, suffix, start=0, end=sys.maxint):
84 return self.data.endswith(suffix, start, end)
Tim Peterse1190062001-01-15 03:34:38 +000085 def expandtabs(self, tabsize=8):
Fred Drakea22b5762000-04-03 03:51:50 +000086 return self.__class__(self.data.expandtabs(tabsize))
Tim Peterse1190062001-01-15 03:34:38 +000087 def find(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +000088 return self.data.find(sub, start, end)
Tim Peterse1190062001-01-15 03:34:38 +000089 def index(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +000090 return self.data.index(sub, start, end)
Jeremy Hyltonfd547572000-07-10 17:07:17 +000091 def isalpha(self): return self.data.isalpha()
92 def isalnum(self): return self.data.isalnum()
Fred Drakea22b5762000-04-03 03:51:50 +000093 def isdecimal(self): return self.data.isdecimal()
94 def isdigit(self): return self.data.isdigit()
95 def islower(self): return self.data.islower()
96 def isnumeric(self): return self.data.isnumeric()
97 def isspace(self): return self.data.isspace()
98 def istitle(self): return self.data.istitle()
99 def isupper(self): return self.data.isupper()
100 def join(self, seq): return self.data.join(seq)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000101 def ljust(self, width, *args):
102 return self.__class__(self.data.ljust(width, *args))
Fred Drakea22b5762000-04-03 03:51:50 +0000103 def lower(self): return self.__class__(self.data.lower())
Neal Norwitzffe33b72003-04-10 22:35:32 +0000104 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
Fredrik Lundha26de2a2006-05-26 19:23:21 +0000105 def partition(self, sep):
106 return self.data.partition(sep)
Tim Peterse1190062001-01-15 03:34:38 +0000107 def replace(self, old, new, maxsplit=-1):
Fred Drakea22b5762000-04-03 03:51:50 +0000108 return self.__class__(self.data.replace(old, new, maxsplit))
Tim Peterse1190062001-01-15 03:34:38 +0000109 def rfind(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000110 return self.data.rfind(sub, start, end)
Tim Peterse1190062001-01-15 03:34:38 +0000111 def rindex(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000112 return self.data.rindex(sub, start, end)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000113 def rjust(self, width, *args):
114 return self.__class__(self.data.rjust(width, *args))
Fredrik Lundha26de2a2006-05-26 19:23:21 +0000115 def rpartition(self, sep):
116 return self.data.rpartition(sep)
Neal Norwitzffe33b72003-04-10 22:35:32 +0000117 def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
Tim Peterse1190062001-01-15 03:34:38 +0000118 def split(self, sep=None, maxsplit=-1):
Fred Drakea22b5762000-04-03 03:51:50 +0000119 return self.data.split(sep, maxsplit)
Hye-Shik Changeebb6412003-12-15 19:46:09 +0000120 def rsplit(self, sep=None, maxsplit=-1):
121 return self.data.rsplit(sep, maxsplit)
Guido van Rossum86662912000-04-11 15:38:46 +0000122 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
Tim Peterse1190062001-01-15 03:34:38 +0000123 def startswith(self, prefix, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000124 return self.data.startswith(prefix, start, end)
Neal Norwitzffe33b72003-04-10 22:35:32 +0000125 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
Fred Drakea22b5762000-04-03 03:51:50 +0000126 def swapcase(self): return self.__class__(self.data.swapcase())
127 def title(self): return self.__class__(self.data.title())
Tim Peterse1190062001-01-15 03:34:38 +0000128 def translate(self, *args):
Fred Drakea8939572000-08-21 21:47:20 +0000129 return self.__class__(self.data.translate(*args))
Fred Drakea22b5762000-04-03 03:51:50 +0000130 def upper(self): return self.__class__(self.data.upper())
Walter Dörwald068325e2002-04-15 13:36:47 +0000131 def zfill(self, width): return self.__class__(self.data.zfill(width))
Fred Drakea22b5762000-04-03 03:51:50 +0000132
Raymond Hettinger882a4162008-02-07 03:25:46 +0000133class MutableString(UserString, collections.MutableSequence):
Fred Drakea22b5762000-04-03 03:51:50 +0000134 """mutable string objects
135
136 Python strings are immutable objects. This has the advantage, that
137 strings may be used as dictionary keys. If this property isn't needed
138 and you insist on changing string values in place instead, you may cheat
139 and use MutableString.
140
141 But the purpose of this class is an educational one: to prevent
142 people from inventing their own mutable string class derived
143 from UserString and than forget thereby to remove (override) the
Thomas Heller611dbc32003-08-27 10:48:12 +0000144 __hash__ method inherited from UserString. This would lead to
Fred Drakea22b5762000-04-03 03:51:50 +0000145 errors that would be very hard to track down.
146
147 A faster and better solution is to rewrite your program using lists."""
148 def __init__(self, string=""):
149 self.data = string
Tim Peterse1190062001-01-15 03:34:38 +0000150 def __hash__(self):
Fred Drakea22b5762000-04-03 03:51:50 +0000151 raise TypeError, "unhashable type (it is mutable)"
152 def __setitem__(self, index, sub):
Thomas Wouters3ccec682007-08-28 15:28:19 +0000153 if isinstance(index, slice):
154 if isinstance(sub, UserString):
155 sub = sub.data
156 elif not isinstance(sub, basestring):
157 sub = str(sub)
158 start, stop, step = index.indices(len(self.data))
159 if step == -1:
160 start, stop = stop+1, start+1
161 sub = sub[::-1]
162 elif step != 1:
163 # XXX(twouters): I guess we should be reimplementing
164 # the extended slice assignment/deletion algorithm here...
165 raise TypeError, "invalid step in slicing assignment"
166 start = min(start, stop)
167 self.data = self.data[:start] + sub + self.data[stop:]
168 else:
169 if index < 0:
170 index += len(self.data)
171 if index < 0 or index >= len(self.data): raise IndexError
172 self.data = self.data[:index] + sub + self.data[index+1:]
Fred Drakea22b5762000-04-03 03:51:50 +0000173 def __delitem__(self, index):
Thomas Wouters3ccec682007-08-28 15:28:19 +0000174 if isinstance(index, slice):
175 start, stop, step = index.indices(len(self.data))
176 if step == -1:
177 start, stop = stop+1, start+1
178 elif step != 1:
179 # XXX(twouters): see same block in __setitem__
180 raise TypeError, "invalid step in slicing deletion"
181 start = min(start, stop)
182 self.data = self.data[:start] + self.data[stop:]
183 else:
184 if index < 0:
185 index += len(self.data)
186 if index < 0 or index >= len(self.data): raise IndexError
187 self.data = self.data[:index] + self.data[index+1:]
Fred Drakea22b5762000-04-03 03:51:50 +0000188 def __setslice__(self, start, end, sub):
189 start = max(start, 0); end = max(end, 0)
190 if isinstance(sub, UserString):
191 self.data = self.data[:start]+sub.data+self.data[end:]
Neal Norwitz418b97e2006-06-12 02:07:24 +0000192 elif isinstance(sub, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +0000193 self.data = self.data[:start]+sub+self.data[end:]
194 else:
195 self.data = self.data[:start]+str(sub)+self.data[end:]
196 def __delslice__(self, start, end):
197 start = max(start, 0); end = max(end, 0)
198 self.data = self.data[:start] + self.data[end:]
199 def immutable(self):
200 return UserString(self.data)
Raymond Hettingerc35491e2002-08-09 01:37:06 +0000201 def __iadd__(self, other):
202 if isinstance(other, UserString):
203 self.data += other.data
Neal Norwitz418b97e2006-06-12 02:07:24 +0000204 elif isinstance(other, basestring):
Raymond Hettingerc35491e2002-08-09 01:37:06 +0000205 self.data += other
206 else:
207 self.data += str(other)
208 return self
209 def __imul__(self, n):
210 self.data *= n
211 return self
Raymond Hettinger882a4162008-02-07 03:25:46 +0000212 def insert(self, index, value):
213 self[index:index] = value
214
Fred Drakea22b5762000-04-03 03:51:50 +0000215if __name__ == "__main__":
216 # execute the regression test to stdout, if called as a script:
217 import os
218 called_in_dir, called_as = os.path.split(sys.argv[0])
Fred Drakea22b5762000-04-03 03:51:50 +0000219 called_as, py = os.path.splitext(called_as)
Fred Drakea22b5762000-04-03 03:51:50 +0000220 if '-q' in sys.argv:
Barry Warsaw408b6d32002-07-30 23:27:12 +0000221 from test import test_support
Fred Drakea22b5762000-04-03 03:51:50 +0000222 test_support.verbose = 0
Barry Warsaw408b6d32002-07-30 23:27:12 +0000223 __import__('test.test_' + called_as.lower())