blob: 60dc34bc4b3c2791d4d100dfc6f6f9332e09dc27 [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
9
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000010__all__ = ["UserString","MutableString"]
11
Fred Drakea22b5762000-04-03 03:51:50 +000012class UserString:
13 def __init__(self, seq):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014 if isinstance(seq, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000015 self.data = seq
16 elif isinstance(seq, UserString):
17 self.data = seq.data[:]
Tim Peterse1190062001-01-15 03:34:38 +000018 else:
Fred Drakea22b5762000-04-03 03:51:50 +000019 self.data = str(seq)
20 def __str__(self): return str(self.data)
21 def __repr__(self): return repr(self.data)
22 def __int__(self): return int(self.data)
23 def __long__(self): return long(self.data)
24 def __float__(self): return float(self.data)
25 def __complex__(self): return complex(self.data)
26 def __hash__(self): return hash(self.data)
27
28 def __cmp__(self, string):
29 if isinstance(string, UserString):
30 return cmp(self.data, string.data)
31 else:
32 return cmp(self.data, string)
33 def __contains__(self, char):
34 return char in self.data
35
36 def __len__(self): return len(self.data)
37 def __getitem__(self, index): return self.__class__(self.data[index])
38 def __getslice__(self, start, end):
39 start = max(start, 0); end = max(end, 0)
40 return self.__class__(self.data[start:end])
41
42 def __add__(self, other):
43 if isinstance(other, UserString):
44 return self.__class__(self.data + other.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 elif isinstance(other, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000046 return self.__class__(self.data + other)
47 else:
48 return self.__class__(self.data + str(other))
49 def __radd__(self, other):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 if isinstance(other, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +000051 return self.__class__(other + self.data)
52 else:
53 return self.__class__(str(other) + self.data)
54 def __mul__(self, n):
55 return self.__class__(self.data*n)
56 __rmul__ = __mul__
Neil Schemenauerfe4f7692002-11-18 16:12:54 +000057 def __mod__(self, args):
58 return self.__class__(self.data % args)
Fred Drakea22b5762000-04-03 03:51:50 +000059
60 # the following methods are defined in alphabetical order:
61 def capitalize(self): return self.__class__(self.data.capitalize())
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000062 def center(self, width, *args):
63 return self.__class__(self.data.center(width, *args))
Fred Drakea22b5762000-04-03 03:51:50 +000064 def count(self, sub, start=0, end=sys.maxint):
65 return self.data.count(sub, start, end)
Marc-André Lemburg2d920412001-05-15 12:00:02 +000066 def decode(self, encoding=None, errors=None): # XXX improve this?
67 if encoding:
68 if errors:
69 return self.__class__(self.data.decode(encoding, errors))
70 else:
71 return self.__class__(self.data.decode(encoding))
72 else:
73 return self.__class__(self.data.decode())
Fred Drakea22b5762000-04-03 03:51:50 +000074 def encode(self, encoding=None, errors=None): # XXX improve this?
75 if encoding:
76 if errors:
77 return self.__class__(self.data.encode(encoding, errors))
78 else:
79 return self.__class__(self.data.encode(encoding))
Tim Peterse1190062001-01-15 03:34:38 +000080 else:
Fred Drakea22b5762000-04-03 03:51:50 +000081 return self.__class__(self.data.encode())
82 def endswith(self, suffix, start=0, end=sys.maxint):
83 return self.data.endswith(suffix, start, end)
Tim Peterse1190062001-01-15 03:34:38 +000084 def expandtabs(self, tabsize=8):
Fred Drakea22b5762000-04-03 03:51:50 +000085 return self.__class__(self.data.expandtabs(tabsize))
Tim Peterse1190062001-01-15 03:34:38 +000086 def find(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +000087 return self.data.find(sub, start, end)
Tim Peterse1190062001-01-15 03:34:38 +000088 def index(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +000089 return self.data.index(sub, start, end)
Jeremy Hyltonfd547572000-07-10 17:07:17 +000090 def isalpha(self): return self.data.isalpha()
91 def isalnum(self): return self.data.isalnum()
Fred Drakea22b5762000-04-03 03:51:50 +000092 def isdecimal(self): return self.data.isdecimal()
93 def isdigit(self): return self.data.isdigit()
94 def islower(self): return self.data.islower()
95 def isnumeric(self): return self.data.isnumeric()
96 def isspace(self): return self.data.isspace()
97 def istitle(self): return self.data.istitle()
98 def isupper(self): return self.data.isupper()
99 def join(self, seq): return self.data.join(seq)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000100 def ljust(self, width, *args):
101 return self.__class__(self.data.ljust(width, *args))
Fred Drakea22b5762000-04-03 03:51:50 +0000102 def lower(self): return self.__class__(self.data.lower())
Neal Norwitzffe33b72003-04-10 22:35:32 +0000103 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000104 def partition(self, sep):
105 return self.data.partition(sep)
Tim Peterse1190062001-01-15 03:34:38 +0000106 def replace(self, old, new, maxsplit=-1):
Fred Drakea22b5762000-04-03 03:51:50 +0000107 return self.__class__(self.data.replace(old, new, maxsplit))
Tim Peterse1190062001-01-15 03:34:38 +0000108 def rfind(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000109 return self.data.rfind(sub, start, end)
Tim Peterse1190062001-01-15 03:34:38 +0000110 def rindex(self, sub, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000111 return self.data.rindex(sub, start, end)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000112 def rjust(self, width, *args):
113 return self.__class__(self.data.rjust(width, *args))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000114 def rpartition(self, sep):
115 return self.data.rpartition(sep)
Neal Norwitzffe33b72003-04-10 22:35:32 +0000116 def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
Tim Peterse1190062001-01-15 03:34:38 +0000117 def split(self, sep=None, maxsplit=-1):
Fred Drakea22b5762000-04-03 03:51:50 +0000118 return self.data.split(sep, maxsplit)
Hye-Shik Changeebb6412003-12-15 19:46:09 +0000119 def rsplit(self, sep=None, maxsplit=-1):
120 return self.data.rsplit(sep, maxsplit)
Guido van Rossum86662912000-04-11 15:38:46 +0000121 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
Tim Peterse1190062001-01-15 03:34:38 +0000122 def startswith(self, prefix, start=0, end=sys.maxint):
Fred Drakea22b5762000-04-03 03:51:50 +0000123 return self.data.startswith(prefix, start, end)
Neal Norwitzffe33b72003-04-10 22:35:32 +0000124 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
Fred Drakea22b5762000-04-03 03:51:50 +0000125 def swapcase(self): return self.__class__(self.data.swapcase())
126 def title(self): return self.__class__(self.data.title())
Tim Peterse1190062001-01-15 03:34:38 +0000127 def translate(self, *args):
Fred Drakea8939572000-08-21 21:47:20 +0000128 return self.__class__(self.data.translate(*args))
Fred Drakea22b5762000-04-03 03:51:50 +0000129 def upper(self): return self.__class__(self.data.upper())
Walter Dörwald068325e2002-04-15 13:36:47 +0000130 def zfill(self, width): return self.__class__(self.data.zfill(width))
Fred Drakea22b5762000-04-03 03:51:50 +0000131
132class MutableString(UserString):
133 """mutable string objects
134
135 Python strings are immutable objects. This has the advantage, that
136 strings may be used as dictionary keys. If this property isn't needed
137 and you insist on changing string values in place instead, you may cheat
138 and use MutableString.
139
140 But the purpose of this class is an educational one: to prevent
141 people from inventing their own mutable string class derived
142 from UserString and than forget thereby to remove (override) the
Thomas Heller611dbc32003-08-27 10:48:12 +0000143 __hash__ method inherited from UserString. This would lead to
Fred Drakea22b5762000-04-03 03:51:50 +0000144 errors that would be very hard to track down.
145
146 A faster and better solution is to rewrite your program using lists."""
147 def __init__(self, string=""):
148 self.data = string
Tim Peterse1190062001-01-15 03:34:38 +0000149 def __hash__(self):
Fred Drakea22b5762000-04-03 03:51:50 +0000150 raise TypeError, "unhashable type (it is mutable)"
151 def __setitem__(self, index, sub):
Walter Dörwaldaf3b39a2005-02-18 13:22:43 +0000152 if index < 0:
Tim Peterseba28be2005-03-28 01:08:02 +0000153 index += len(self.data)
Fred Drakea22b5762000-04-03 03:51:50 +0000154 if index < 0 or index >= len(self.data): raise IndexError
155 self.data = self.data[:index] + sub + self.data[index+1:]
156 def __delitem__(self, index):
Walter Dörwaldaf3b39a2005-02-18 13:22:43 +0000157 if index < 0:
Tim Peterseba28be2005-03-28 01:08:02 +0000158 index += len(self.data)
Fred Drakea22b5762000-04-03 03:51:50 +0000159 if index < 0 or index >= len(self.data): raise IndexError
160 self.data = self.data[:index] + self.data[index+1:]
161 def __setslice__(self, start, end, sub):
162 start = max(start, 0); end = max(end, 0)
163 if isinstance(sub, UserString):
164 self.data = self.data[:start]+sub.data+self.data[end:]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000165 elif isinstance(sub, basestring):
Fred Drakea22b5762000-04-03 03:51:50 +0000166 self.data = self.data[:start]+sub+self.data[end:]
167 else:
168 self.data = self.data[:start]+str(sub)+self.data[end:]
169 def __delslice__(self, start, end):
170 start = max(start, 0); end = max(end, 0)
171 self.data = self.data[:start] + self.data[end:]
172 def immutable(self):
173 return UserString(self.data)
Raymond Hettingerc35491e2002-08-09 01:37:06 +0000174 def __iadd__(self, other):
175 if isinstance(other, UserString):
176 self.data += other.data
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 elif isinstance(other, basestring):
Raymond Hettingerc35491e2002-08-09 01:37:06 +0000178 self.data += other
179 else:
180 self.data += str(other)
181 return self
182 def __imul__(self, n):
183 self.data *= n
184 return self
Tim Peterse1190062001-01-15 03:34:38 +0000185
Fred Drakea22b5762000-04-03 03:51:50 +0000186if __name__ == "__main__":
187 # execute the regression test to stdout, if called as a script:
188 import os
189 called_in_dir, called_as = os.path.split(sys.argv[0])
Fred Drakea22b5762000-04-03 03:51:50 +0000190 called_as, py = os.path.splitext(called_as)
Fred Drakea22b5762000-04-03 03:51:50 +0000191 if '-q' in sys.argv:
Barry Warsaw408b6d32002-07-30 23:27:12 +0000192 from test import test_support
Fred Drakea22b5762000-04-03 03:51:50 +0000193 test_support.verbose = 0
Barry Warsaw408b6d32002-07-30 23:27:12 +0000194 __import__('test.test_' + called_as.lower())