This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Lib / UserString.py
blob45cdeb5d411779747f75c190faf5003434c0f3a9
1 #!/usr/bin/env python
2 ## vim:ts=4:et:nowrap
3 """A user-defined wrapper around string objects
5 Note: string objects have grown methods in Python 1.6
6 This module requires Python 1.6 or later.
7 """
8 from types import StringType, UnicodeType
9 import sys
11 __all__ = ["UserString","MutableString"]
13 class UserString:
14 def __init__(self, seq):
15 if isinstance(seq, StringType) or isinstance(seq, UnicodeType):
16 self.data = seq
17 elif isinstance(seq, UserString):
18 self.data = seq.data[:]
19 else:
20 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)
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
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])
43 def __add__(self, other):
44 if isinstance(other, UserString):
45 return self.__class__(self.data + other.data)
46 elif isinstance(other, StringType) or isinstance(other, UnicodeType):
47 return self.__class__(self.data + other)
48 else:
49 return self.__class__(self.data + str(other))
50 def __radd__(self, other):
51 if isinstance(other, StringType) or isinstance(other, UnicodeType):
52 return self.__class__(other + self.data)
53 else:
54 return self.__class__(str(other) + self.data)
55 def __iadd__(self, other):
56 if isinstance(other, UserString):
57 self.data += other.data
58 elif isinstance(other, StringType) or isinstance(other, UnicodeType):
59 self.data += other
60 else:
61 self.data += str(other)
62 return self
63 def __mul__(self, n):
64 return self.__class__(self.data*n)
65 __rmul__ = __mul__
66 def __imul__(self, n):
67 self.data *= n
68 return self
70 # the following methods are defined in alphabetical order:
71 def capitalize(self): return self.__class__(self.data.capitalize())
72 def center(self, width): return self.__class__(self.data.center(width))
73 def count(self, sub, start=0, end=sys.maxint):
74 return self.data.count(sub, start, end)
75 def decode(self, encoding=None, errors=None): # XXX improve this?
76 if encoding:
77 if errors:
78 return self.__class__(self.data.decode(encoding, errors))
79 else:
80 return self.__class__(self.data.decode(encoding))
81 else:
82 return self.__class__(self.data.decode())
83 def encode(self, encoding=None, errors=None): # XXX improve this?
84 if encoding:
85 if errors:
86 return self.__class__(self.data.encode(encoding, errors))
87 else:
88 return self.__class__(self.data.encode(encoding))
89 else:
90 return self.__class__(self.data.encode())
91 def endswith(self, suffix, start=0, end=sys.maxint):
92 return self.data.endswith(suffix, start, end)
93 def expandtabs(self, tabsize=8):
94 return self.__class__(self.data.expandtabs(tabsize))
95 def find(self, sub, start=0, end=sys.maxint):
96 return self.data.find(sub, start, end)
97 def index(self, sub, start=0, end=sys.maxint):
98 return self.data.index(sub, start, end)
99 def isalpha(self): return self.data.isalpha()
100 def isalnum(self): return self.data.isalnum()
101 def isdecimal(self): return self.data.isdecimal()
102 def isdigit(self): return self.data.isdigit()
103 def islower(self): return self.data.islower()
104 def isnumeric(self): return self.data.isnumeric()
105 def isspace(self): return self.data.isspace()
106 def istitle(self): return self.data.istitle()
107 def isupper(self): return self.data.isupper()
108 def join(self, seq): return self.data.join(seq)
109 def ljust(self, width): return self.__class__(self.data.ljust(width))
110 def lower(self): return self.__class__(self.data.lower())
111 def lstrip(self): return self.__class__(self.data.lstrip())
112 def replace(self, old, new, maxsplit=-1):
113 return self.__class__(self.data.replace(old, new, maxsplit))
114 def rfind(self, sub, start=0, end=sys.maxint):
115 return self.data.rfind(sub, start, end)
116 def rindex(self, sub, start=0, end=sys.maxint):
117 return self.data.rindex(sub, start, end)
118 def rjust(self, width): return self.__class__(self.data.rjust(width))
119 def rstrip(self): return self.__class__(self.data.rstrip())
120 def split(self, sep=None, maxsplit=-1):
121 return self.data.split(sep, maxsplit)
122 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
123 def startswith(self, prefix, start=0, end=sys.maxint):
124 return self.data.startswith(prefix, start, end)
125 def strip(self): return self.__class__(self.data.strip())
126 def swapcase(self): return self.__class__(self.data.swapcase())
127 def title(self): return self.__class__(self.data.title())
128 def translate(self, *args):
129 return self.__class__(self.data.translate(*args))
130 def upper(self): return self.__class__(self.data.upper())
132 class MutableString(UserString):
133 """mutable string objects
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.
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
143 __hash__ method inherited from ^UserString. This would lead to
144 errors that would be very hard to track down.
146 A faster and better solution is to rewrite your program using lists."""
147 def __init__(self, string=""):
148 self.data = string
149 def __hash__(self):
150 raise TypeError, "unhashable type (it is mutable)"
151 def __setitem__(self, index, sub):
152 if index < 0 or index >= len(self.data): raise IndexError
153 self.data = self.data[:index] + sub + self.data[index+1:]
154 def __delitem__(self, index):
155 if index < 0 or index >= len(self.data): raise IndexError
156 self.data = self.data[:index] + self.data[index+1:]
157 def __setslice__(self, start, end, sub):
158 start = max(start, 0); end = max(end, 0)
159 if isinstance(sub, UserString):
160 self.data = self.data[:start]+sub.data+self.data[end:]
161 elif isinstance(sub, StringType) or isinstance(sub, UnicodeType):
162 self.data = self.data[:start]+sub+self.data[end:]
163 else:
164 self.data = self.data[:start]+str(sub)+self.data[end:]
165 def __delslice__(self, start, end):
166 start = max(start, 0); end = max(end, 0)
167 self.data = self.data[:start] + self.data[end:]
168 def immutable(self):
169 return UserString(self.data)
171 if __name__ == "__main__":
172 # execute the regression test to stdout, if called as a script:
173 import os
174 called_in_dir, called_as = os.path.split(sys.argv[0])
175 called_in_dir = os.path.abspath(called_in_dir)
176 called_as, py = os.path.splitext(called_as)
177 sys.path.append(os.path.join(called_in_dir, 'test'))
178 if '-q' in sys.argv:
179 import test_support
180 test_support.verbose = 0
181 __import__('test_' + called_as.lower())