UserString.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #!/usr/bin/env python
  2. ## vim:ts=4:et:nowrap
  3. """A user-defined wrapper around string objects
  4. Note: string objects have grown methods in Python 1.6
  5. This module requires Python 1.6 or later.
  6. """
  7. import sys
  8. import collections
  9. __all__ = ["UserString","MutableString"]
  10. class UserString(collections.Sequence):
  11. def __init__(self, seq):
  12. if isinstance(seq, basestring):
  13. self.data = seq
  14. elif isinstance(seq, UserString):
  15. self.data = seq.data[:]
  16. else:
  17. self.data = str(seq)
  18. def __str__(self): return str(self.data)
  19. def __repr__(self): return repr(self.data)
  20. def __int__(self): return int(self.data)
  21. def __long__(self): return long(self.data)
  22. def __float__(self): return float(self.data)
  23. def __complex__(self): return complex(self.data)
  24. def __hash__(self): return hash(self.data)
  25. def __cmp__(self, string):
  26. if isinstance(string, UserString):
  27. return cmp(self.data, string.data)
  28. else:
  29. return cmp(self.data, string)
  30. def __contains__(self, char):
  31. return char in self.data
  32. def __len__(self): return len(self.data)
  33. def __getitem__(self, index): return self.__class__(self.data[index])
  34. def __getslice__(self, start, end):
  35. start = max(start, 0); end = max(end, 0)
  36. return self.__class__(self.data[start:end])
  37. def __add__(self, other):
  38. if isinstance(other, UserString):
  39. return self.__class__(self.data + other.data)
  40. elif isinstance(other, basestring):
  41. return self.__class__(self.data + other)
  42. else:
  43. return self.__class__(self.data + str(other))
  44. def __radd__(self, other):
  45. if isinstance(other, basestring):
  46. return self.__class__(other + self.data)
  47. else:
  48. return self.__class__(str(other) + self.data)
  49. def __mul__(self, n):
  50. return self.__class__(self.data*n)
  51. __rmul__ = __mul__
  52. def __mod__(self, args):
  53. return self.__class__(self.data % args)
  54. # the following methods are defined in alphabetical order:
  55. def capitalize(self): return self.__class__(self.data.capitalize())
  56. def center(self, width, *args):
  57. return self.__class__(self.data.center(width, *args))
  58. def count(self, sub, start=0, end=sys.maxint):
  59. return self.data.count(sub, start, end)
  60. def decode(self, encoding=None, errors=None): # XXX improve this?
  61. if encoding:
  62. if errors:
  63. return self.__class__(self.data.decode(encoding, errors))
  64. else:
  65. return self.__class__(self.data.decode(encoding))
  66. else:
  67. return self.__class__(self.data.decode())
  68. def encode(self, encoding=None, errors=None): # XXX improve this?
  69. if encoding:
  70. if errors:
  71. return self.__class__(self.data.encode(encoding, errors))
  72. else:
  73. return self.__class__(self.data.encode(encoding))
  74. else:
  75. return self.__class__(self.data.encode())
  76. def endswith(self, suffix, start=0, end=sys.maxint):
  77. return self.data.endswith(suffix, start, end)
  78. def expandtabs(self, tabsize=8):
  79. return self.__class__(self.data.expandtabs(tabsize))
  80. def find(self, sub, start=0, end=sys.maxint):
  81. return self.data.find(sub, start, end)
  82. def index(self, sub, start=0, end=sys.maxint):
  83. return self.data.index(sub, start, end)
  84. def isalpha(self): return self.data.isalpha()
  85. def isalnum(self): return self.data.isalnum()
  86. def isdecimal(self): return self.data.isdecimal()
  87. def isdigit(self): return self.data.isdigit()
  88. def islower(self): return self.data.islower()
  89. def isnumeric(self): return self.data.isnumeric()
  90. def isspace(self): return self.data.isspace()
  91. def istitle(self): return self.data.istitle()
  92. def isupper(self): return self.data.isupper()
  93. def join(self, seq): return self.data.join(seq)
  94. def ljust(self, width, *args):
  95. return self.__class__(self.data.ljust(width, *args))
  96. def lower(self): return self.__class__(self.data.lower())
  97. def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
  98. def partition(self, sep):
  99. return self.data.partition(sep)
  100. def replace(self, old, new, maxsplit=-1):
  101. return self.__class__(self.data.replace(old, new, maxsplit))
  102. def rfind(self, sub, start=0, end=sys.maxint):
  103. return self.data.rfind(sub, start, end)
  104. def rindex(self, sub, start=0, end=sys.maxint):
  105. return self.data.rindex(sub, start, end)
  106. def rjust(self, width, *args):
  107. return self.__class__(self.data.rjust(width, *args))
  108. def rpartition(self, sep):
  109. return self.data.rpartition(sep)
  110. def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
  111. def split(self, sep=None, maxsplit=-1):
  112. return self.data.split(sep, maxsplit)
  113. def rsplit(self, sep=None, maxsplit=-1):
  114. return self.data.rsplit(sep, maxsplit)
  115. def splitlines(self, keepends=0): return self.data.splitlines(keepends)
  116. def startswith(self, prefix, start=0, end=sys.maxint):
  117. return self.data.startswith(prefix, start, end)
  118. def strip(self, chars=None): return self.__class__(self.data.strip(chars))
  119. def swapcase(self): return self.__class__(self.data.swapcase())
  120. def title(self): return self.__class__(self.data.title())
  121. def translate(self, *args):
  122. return self.__class__(self.data.translate(*args))
  123. def upper(self): return self.__class__(self.data.upper())
  124. def zfill(self, width): return self.__class__(self.data.zfill(width))
  125. class MutableString(UserString, collections.MutableSequence):
  126. """mutable string objects
  127. Python strings are immutable objects. This has the advantage, that
  128. strings may be used as dictionary keys. If this property isn't needed
  129. and you insist on changing string values in place instead, you may cheat
  130. and use MutableString.
  131. But the purpose of this class is an educational one: to prevent
  132. people from inventing their own mutable string class derived
  133. from UserString and than forget thereby to remove (override) the
  134. __hash__ method inherited from UserString. This would lead to
  135. errors that would be very hard to track down.
  136. A faster and better solution is to rewrite your program using lists."""
  137. def __init__(self, string=""):
  138. from warnings import warnpy3k
  139. warnpy3k('the class UserString.MutableString has been removed in '
  140. 'Python 3.0', stacklevel=2)
  141. self.data = string
  142. # We inherit object.__hash__, so we must deny this explicitly
  143. __hash__ = None
  144. def __setitem__(self, index, sub):
  145. if isinstance(index, slice):
  146. if isinstance(sub, UserString):
  147. sub = sub.data
  148. elif not isinstance(sub, basestring):
  149. sub = str(sub)
  150. start, stop, step = index.indices(len(self.data))
  151. if step == -1:
  152. start, stop = stop+1, start+1
  153. sub = sub[::-1]
  154. elif step != 1:
  155. # XXX(twouters): I guess we should be reimplementing
  156. # the extended slice assignment/deletion algorithm here...
  157. raise TypeError, "invalid step in slicing assignment"
  158. start = min(start, stop)
  159. self.data = self.data[:start] + sub + self.data[stop:]
  160. else:
  161. if index < 0:
  162. index += len(self.data)
  163. if index < 0 or index >= len(self.data): raise IndexError
  164. self.data = self.data[:index] + sub + self.data[index+1:]
  165. def __delitem__(self, index):
  166. if isinstance(index, slice):
  167. start, stop, step = index.indices(len(self.data))
  168. if step == -1:
  169. start, stop = stop+1, start+1
  170. elif step != 1:
  171. # XXX(twouters): see same block in __setitem__
  172. raise TypeError, "invalid step in slicing deletion"
  173. start = min(start, stop)
  174. self.data = self.data[:start] + self.data[stop:]
  175. else:
  176. if index < 0:
  177. index += len(self.data)
  178. if index < 0 or index >= len(self.data): raise IndexError
  179. self.data = self.data[:index] + self.data[index+1:]
  180. def __setslice__(self, start, end, sub):
  181. start = max(start, 0); end = max(end, 0)
  182. if isinstance(sub, UserString):
  183. self.data = self.data[:start]+sub.data+self.data[end:]
  184. elif isinstance(sub, basestring):
  185. self.data = self.data[:start]+sub+self.data[end:]
  186. else:
  187. self.data = self.data[:start]+str(sub)+self.data[end:]
  188. def __delslice__(self, start, end):
  189. start = max(start, 0); end = max(end, 0)
  190. self.data = self.data[:start] + self.data[end:]
  191. def immutable(self):
  192. return UserString(self.data)
  193. def __iadd__(self, other):
  194. if isinstance(other, UserString):
  195. self.data += other.data
  196. elif isinstance(other, basestring):
  197. self.data += other
  198. else:
  199. self.data += str(other)
  200. return self
  201. def __imul__(self, n):
  202. self.data *= n
  203. return self
  204. def insert(self, index, value):
  205. self[index:index] = value
  206. if __name__ == "__main__":
  207. # execute the regression test to stdout, if called as a script:
  208. import os
  209. called_in_dir, called_as = os.path.split(sys.argv[0])
  210. called_as, py = os.path.splitext(called_as)
  211. if '-q' in sys.argv:
  212. from test import test_support
  213. test_support.verbose = 0
  214. __import__('test.test_' + called_as.lower())