You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UserString.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. from types import StringType, UnicodeType
  8. import sys
  9. __all__ = ["UserString","MutableString"]
  10. class UserString:
  11. def __init__(self, seq):
  12. if isinstance(seq, StringType) or isinstance(seq, UnicodeType):
  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, StringType) or isinstance(other, UnicodeType):
  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, StringType) or isinstance(other, UnicodeType):
  46. return self.__class__(other + self.data)
  47. else:
  48. return self.__class__(str(other) + self.data)
  49. def __iadd__(self, other):
  50. if isinstance(other, UserString):
  51. self.data += other.data
  52. elif isinstance(other, StringType) or isinstance(other, UnicodeType):
  53. self.data += other
  54. else:
  55. self.data += str(other)
  56. return self
  57. def __mul__(self, n):
  58. return self.__class__(self.data*n)
  59. __rmul__ = __mul__
  60. def __imul__(self, n):
  61. self.data *= n
  62. return self
  63. # the following methods are defined in alphabetical order:
  64. def capitalize(self): return self.__class__(self.data.capitalize())
  65. def center(self, width): return self.__class__(self.data.center(width))
  66. def count(self, sub, start=0, end=sys.maxint):
  67. return self.data.count(sub, start, end)
  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): return self.__class__(self.data.ljust(width))
  95. def lower(self): return self.__class__(self.data.lower())
  96. def lstrip(self): return self.__class__(self.data.lstrip())
  97. def replace(self, old, new, maxsplit=-1):
  98. return self.__class__(self.data.replace(old, new, maxsplit))
  99. def rfind(self, sub, start=0, end=sys.maxint):
  100. return self.data.rfind(sub, start, end)
  101. def rindex(self, sub, start=0, end=sys.maxint):
  102. return self.data.rindex(sub, start, end)
  103. def rjust(self, width): return self.__class__(self.data.rjust(width))
  104. def rstrip(self): return self.__class__(self.data.rstrip())
  105. def split(self, sep=None, maxsplit=-1):
  106. return self.data.split(sep, maxsplit)
  107. def splitlines(self, keepends=0): return self.data.splitlines(keepends)
  108. def startswith(self, prefix, start=0, end=sys.maxint):
  109. return self.data.startswith(prefix, start, end)
  110. def strip(self): return self.__class__(self.data.strip())
  111. def swapcase(self): return self.__class__(self.data.swapcase())
  112. def title(self): return self.__class__(self.data.title())
  113. def translate(self, *args):
  114. return self.__class__(self.data.translate(*args))
  115. def upper(self): return self.__class__(self.data.upper())
  116. class MutableString(UserString):
  117. """mutable string objects
  118. Python strings are immutable objects. This has the advantage, that
  119. strings may be used as dictionary keys. If this property isn't needed
  120. and you insist on changing string values in place instead, you may cheat
  121. and use MutableString.
  122. But the purpose of this class is an educational one: to prevent
  123. people from inventing their own mutable string class derived
  124. from UserString and than forget thereby to remove (override) the
  125. __hash__ method inherited from ^UserString. This would lead to
  126. errors that would be very hard to track down.
  127. A faster and better solution is to rewrite your program using lists."""
  128. def __init__(self, string=""):
  129. self.data = string
  130. def __hash__(self):
  131. raise TypeError, "unhashable type (it is mutable)"
  132. def __setitem__(self, index, sub):
  133. if index < 0 or index >= len(self.data): raise IndexError
  134. self.data = self.data[:index] + sub + self.data[index+1:]
  135. def __delitem__(self, index):
  136. if index < 0 or index >= len(self.data): raise IndexError
  137. self.data = self.data[:index] + self.data[index+1:]
  138. def __setslice__(self, start, end, sub):
  139. start = max(start, 0); end = max(end, 0)
  140. if isinstance(sub, UserString):
  141. self.data = self.data[:start]+sub.data+self.data[end:]
  142. elif isinstance(sub, StringType) or isinstance(sub, UnicodeType):
  143. self.data = self.data[:start]+sub+self.data[end:]
  144. else:
  145. self.data = self.data[:start]+str(sub)+self.data[end:]
  146. def __delslice__(self, start, end):
  147. start = max(start, 0); end = max(end, 0)
  148. self.data = self.data[:start] + self.data[end:]
  149. def immutable(self):
  150. return UserString(self.data)
  151. if __name__ == "__main__":
  152. # execute the regression test to stdout, if called as a script:
  153. import os
  154. called_in_dir, called_as = os.path.split(sys.argv[0])
  155. called_in_dir = os.path.abspath(called_in_dir)
  156. called_as, py = os.path.splitext(called_as)
  157. sys.path.append(os.path.join(called_in_dir, 'test'))
  158. if '-q' in sys.argv:
  159. import test_support
  160. test_support.verbose = 0
  161. __import__('test_' + called_as.lower())